Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display the items related to a foreign key
What i want is to display a the name and age of employees here with its department. For like a department header and a list of employee names and age EG: (department name1) name1 age1 name2 age2 (department name2) name3 age3 I am new to django i used One to Many key i dont get what do i do with in my views and url/ html. My Models.py class Department(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Employee(models.Model): name = models.CharField(max_length=200) age = models.CharField(max_length=200) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return self.name My views.py: def index(request: HttpRequest) -> HttpResponse: context = { 'categories': Employee.objects.all() } return render(request, 'index.html', context) My urls.py: path('', views.index), My html: {% for item in categories.all %} {{ item.name }} {{ item.age }} </br> {% endfor %} -
Passing context variable from template to JavaScript file
This thread here discussed using variables in inline JavaScript in templates. If I have a separate .js files containing scripts, sitting in static folder, such as following: utils.js const createButton = (buttonCount) => { containerId = "myContainerId" container = document.getElementById(containerId) for (var i = 0; i < buttonCount; i++) {} newButton = document.createElement("button") newButton.value = "Test" newButton.id = "testButton" + i container.appendChild(newButton) } } createButton(buttonCount) mytemplate.html {% extends "base.html" %} {% load static %} {% block title %}Testpage{% endblock %} {% block content-main %} <link href="{% static "css/mycss.css" %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" /> <div id="myContainerId"></div> <script src="{% static 'js/utils.js' %}"> </script> {% endblock %} If I have a variable buttonCount passed into this template via a view function's context, how do I pass it to the utils.js file to be called by function createButton()? views.py def button_view(request): ... buttonCount = 5 return render(request, 'mytemplate.html', {'buttonCount': buttonCount}) -
Catch-all view break URL patterns in Django
def get_urls(self): urls = super().get_urls() url_patterns = [path("admin_profile", self.admin_view(self.profile_view))] return urls + url_patterns The above method cause the catch-all view to break URL patterns which I route after the admin URLs and cause the following error/exception: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/admin_profile/ Raised by: django.contrib.admin.sites.catch_all_view But this only happen when final_catch_all_view = True in django.contrib.admin.sites.catch_all_view When setting final_catch_all_view = False No error or exception is made, everything went fine. Now my question is how can make the function work when final_catch_all_view = True And this is what docs say about catch_all view: > The new admin catch-all view will break URL patterns routed after the > admin URLs and matching the admin URL prefix. You can either adjust > your URL ordering or, if necessary, set AdminSite.final_catch_all_view > to False, disabling the catch-all view. See What’s new in Django 3.2 > for more details. -
deploy django-app to heroku - Application error
I am trying to deploy my Django app to Heroku. I am following all the steps mentioned on Heroku dev center https://devcenter.heroku.com/articles/django-app-configuration. The app deploys successfully but when I run heroku open or manually visit the link it shows Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail My Logs: 2021-07-13T18:26:37.515968+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-07-13T18:26:37.515969+00:00 app[web.1]: self.callable = self.load() 2021-07-13T18:26:37.515969+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-07-13T18:26:37.515970+00:00 app[web.1]: return self.load_wsgiapp() 2021-07-13T18:26:37.515970+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-07-13T18:26:37.515970+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-07-13T18:26:37.515970+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2021-07-13T18:26:37.515971+00:00 app[web.1]: mod = importlib.import_module(module) 2021-07-13T18:26:37.515971+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-07-13T18:26:37.515972+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-07-13T18:26:37.515972+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-07-13T18:26:37.515973+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-07-13T18:26:37.515973+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked 2021-07-13T18:26:37.515973+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-07-13T18:26:37.515974+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-07-13T18:26:37.515974+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-07-13T18:26:37.515974+00:00 … -
Getting a "'str' object has no attribute 'get'" error in Django Python
Some context: I am trying to create an email verification system in Django. I have already made the register/sign-in/log-out views and they work but I have added the verification system to them. I am getting the error after submitting the registration form. I think that the error is happening after the form submission where I am sending the email. The error I am getting is: 'str' object has no attribute 'get' Here is the relevant code: Views: def register(request): if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): inst = form.save() uidb64 = urlsafe_base64_encode(force_bytes(inst.id)) domain = get_current_site(request).domain link = reverse('verify_email', kwargs={'uidb64': uidb64, 'token': token_generator.make_token(inst)}) activate_url = 'http://' + domain + link print(activate_url) #prints the correct link email_subject = 'Verify Your Email' email_body = 'Hello ' + inst.username + '\nClick the link to verify your email\n' + activate_url email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [inst.email], ) return reverse('verify_email_intro', kwargs={'user_id': inst.id}) else: form = CreateUserForm() return render(request, 'users/register.html', {'title_page': 'Register', 'form': form}) @csrf_exempt def verify_email_intro(request, user_id): context = { 'user_id': user_id, } return render(request, 'users/verify_email.html', context) def verify_email(request, uidb64, token): try: pk = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(id=pk) if user.is_active: return redirect('login') else: user.is_active = True user.save() except Exception as ex: pass return … -
Django many to many serializers circular dependency work around?
I have two models, publications and articles, that are connected to each other by a ManyToManyField. Models shown below class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField('Publication') class Publication(models.Model): title = models.CharField(max_length=30) I want to reference articles to publication and publications to articles in both model serializers. class PublicationSerializer(serializers.ModelSerializer): title = serializers.CharField() articles = ??? class Meta: model = Publication fields = ['title', 'articles'] class ArticleSerializer(serializers.ModelSerializer): headline = serializers.CharField() publications = PublicationSerializer(many=True) class Meta: model = Article fields = ['headline', 'publications'] I have been looking up various solutions, many refer to using Relational Fields, such as StringRelatedField, and saw a different solution using SerializerMethodField(), but there doesn't appear to be much documentation on them. Any examples or solutions to this issue? -
Adding custom QuerySet to UserModel causes makemigrations exception
I would like to create a custom queryset for my User model. However, I cannot simply use objects = UserQuerySet.as_manager() since the standard Django User model already has a custom UserManager. My code is simply : class UserQuerySet(MyBaseQuerySet): def opted_out_method(self): return class User(AbstractUser): objects = UserManager.from_queryset(UserQuerySet)() # etc... This code works, except when I do this: $manage.py makemigrations --dry-run File "./manage.py", line 49, in <module> execute_from_command_line(sys.argv) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 164, in handle changes = autodetector.changes( File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/autodetector.py", line 43, in changes changes = self._detect_changes(convert_apps, graph) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/autodetector.py", line 129, in _detect_changes self.new_apps = self.to_state.apps File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 210, in apps return StateApps(self.real_apps, self.models) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 273, in __init__ self.render_multiple([*models.values(), *self.real_models]) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 308, in render_multiple model.render(self) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 577, in render body.update(self.construct_managers()) File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 536, in construct_managers as_manager, manager_path, qs_path, args, kwargs = manager.deconstruct() File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 61, in deconstruct raise ValueError( The … -
How can I add my custom model function's value in my API
So trying to build my own poll app and the models have a lot of relation with each other and I need to count how many objects are in relation with some other objects so I need these custom function for it here's the model with the costume functions class Poll(models.Model): title = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_available = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title @property def total_votes(self): votes = 0 for o in self.option_set.all(): votes = votes + o.how_much_vote return votes @property def users_involved(self): list = [] for o in self.option_set.all(): for v in o.vote: list.append(v.user) return list @property def users_involved(self): users = [] for o in self.option_set.all(): for v in o.who_voted: users.append(v) return users @property def total_votes_each_option(self): dct = {} for o in self.option_set.all(): dct[o.title]= o.how_much_vote return dct My question is how do you include all of those custom functions total_votes, users_involved, etc to my api? because right now my api looks something like this: { "id": 1, "title": "Which is the best frontend framework?", "is_active": true, "is_available": true, "date_created": "2021-07-13T14:08:17.709054Z" } which is expected but I want to know how do I add those extra value to make it look like this { "id": 1, … -
Can saving a model fail after pre_save?
I have a pre_save signal set up for my User model that does something before a User is saved. My question is, will a User.save() function ever fail after the pre_save has already been executed? Basically I'm doing something in the pre_save that I wouldn't want to do if the User.save() fails. Should I be worried about this corner case? NOTE: I cannot use post_save because I need the pre_save instance object. -
How to get data from mysql reverse foreign key without using the prefetch concept?
I have two models, Like, class User(models.Model): fname = models.CharField(max_length=32, blank=True, null=True) class Meta: managed = True db_table = 'u_users' class Email(models.Model): usr_id = models.ForeignKey(User, db_column='usr_id', related_name='emails', on_delete=models.CASCADE) email = models.EmailField(max_length=64) class Meta: managed = True db_table = 'u_email' Now i'would like to get list of users with list of email each users have Sample output. [ { "id":1, "fname":"Test User", "emails":[ { "id":1, "email":"masstmp+2ffj7@gmail.com" }, { "id":2, "email":"masstmp+2ffj8@gmail.com" } ] }, { "id":2, "fname":"Test User2", "emails":[ { "id":3, "email":"masstmp+2ffj9@gmail.com" }, { "id":4, "email":"masstmp+2ffj10@gmail.com" } ] } ] But i need to get this output using single query. In raw query i able to write the query and get the output easy. But i want to know about how to do this in ORM. Please, Thank you. -
Django: Call a function in views.py on HTML form submit
I am building a geospatial web app and am currently trying to implement a date form input to display data from different dates. Each data point is an Object stored in the database, and my frontend uses OpenLayers in javascript. Data is passed from views.py to javascript as a geojson file. Since it's a map, I would effectively like everything to stay in the same view and URL (asides from some GET parameters in the URL). The flow that I'm thinking of goes like: 'Submit' button is clicked on GET form Function in views.py (or somewhere else) is called with parameters from the GET form A query is made to the database to filter by date, and creates a geojson file of the points Geojson is given to javascript to display All the posts I've seen about this problem include calling a different view, can I do all this in the same view? Thank you! -
Hello DevOps, I m getting Application error on Heroku after successful push. Need your help to fix that
I Followed heroku Docs https://devcenter.heroku.com/articles/getting-started-with-python#deploy-the-app to push my app directly from terminal. But after successful deployment on https://secure-brook-21764.herokuapp.com/ but there is application error. these are heroku logs --tail $ heroku logs --tail » Warning: heroku update available from 7.53.0 to 7.54.1. 2021-07-13T17:41:57.282928+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 675, in __getitem__ 2021-07-13T17:41:57.282929+00:00 app[web.1]: raise KeyError(key) from None 2021-07-13T17:41:57.282929+00:00 app[web.1]: KeyError: 'DATABASE_ENGINE' 2021-07-13T17:41:57.282930+00:00 app[web.1]: 2021-07-13T17:41:57.282930+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2021-07-13T17:41:57.282931+00:00 app[web.1]: 2021-07-13T17:41:57.282931+00:00 app[web.1]: Traceback (most recent call last): 2021-07-13T17:41:57.282932+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-07-13T17:41:57.282932+00:00 app[web.1]: worker.init_process() 2021-07-13T17:41:57.282932+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-07-13T17:41:57.282933+00:00 app[web.1]: self.load_wsgi() 2021-07-13T17:41:57.282933+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-07-13T17:41:57.282934+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-07-13T17:41:57.282934+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-07-13T17:41:57.282935+00:00 app[web.1]: self.callable = self.load() 2021-07-13T17:41:57.282935+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-07-13T17:41:57.282936+00:00 app[web.1]: return self.load_wsgiapp() 2021-07-13T17:41:57.282936+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-07-13T17:41:57.282936+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-07-13T17:41:57.282937+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app 2021-07-13T17:41:57.282937+00:00 app[web.1]: mod = importlib.import_module(module) 2021-07-13T17:41:57.282938+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-07-13T17:41:57.282942+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-07-13T17:41:57.282942+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-07-13T17:41:57.282943+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-07-13T17:41:57.282943+00:00 app[web.1]: … -
What is most optimal way to include data science visualizations and/or simple charts in django?
I am new in django, I have achieved to built a simple website up running in my local sever, but now I have reached that part where I want to add some cool and nice looking graphs to my project, but I see many options that are not that simple, if I could choose, I would use some python-based library or something, but it needs to load very fast. I am looking for guidance and suggestions. Thank you in advance. -
Travis Cl builds failing Python/Django
New dev here and am working on a course that has me using Docker and Travis Cl to build a restful API. My builds started off fine, but am now currently getting constant build failures (possible note of relevance, did have a small power outage and after ran docker-compose build again). I've looked and cannot for the life of me figure out what I'm missing at this point. Any advice appreciated. Please let me know if you need any other info. TIA Worker information 0.17s0.00s0.01s0.00s0.01s system_info Build system information 0.02s0.01s0.46s0.23s0.05s0.00s0.04s0.00s0.01s0.01s0.01s0.01s0.01s0.00s0.00s0.03s0.00s0.01s0.36s0.00s0.00s0.00s0.01s0.01s0.10s0.01s0.82s0.00s0.12s6.03s0.00s2.79s0.00s2.61s docker_mtu_and_registry_mirrors resolvconf services 3.02s$ sudo systemctl start docker git.checkout 0.41s$ git clone --depth=50 --branch=main https://github.com/Ash-Renee/Recipe-App-API.git Ash-Renee/Recipe-App-API 0.01s Setting environment variables from repository settings $ export DOCKER_USERNAME=[secure] $ export DOCKER_PASSWORD=[secure] 0.01s$ source ~/virtualenv/python3.6/bin/activate $ python --version Python 3.6.7 $ pip --version pip 20.1.1 from /home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pip (python 3.6) before_install 0.61s$ echo $DOCKER_PASSWORD | docker login --username $DOCKER_USERNAME --password-stdin Pip version 20.3 introduces changes to the dependency resolver that may affect your software. We advise you to consider testing the upcoming changes, which may be introduced in a future Travis CI build image update. See https://pip.pypa.io/en/latest/user_guide/#changes-to-the-pip-dependency-resolver-in-20-2-2020 for more information. install 6.66s$ pip install -r requirements.txt before_script 7.59s$ pip install docker-compose 17.50s$ docker-compose run … -
want to load models content in html django
i have a model name section connected with other model name subject with foreign key what i want to do is i want to load half of it content in other page and half of it content on other html my models.py class Section(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='section') sub_section = models.CharField(max_length=500, blank=True) title = models.CharField(max_length=5000, blank=False) teacher = models.CharField(max_length=500, blank=False) file = models.FileField(upload_to='section_vedios', blank=False) about_section = models.TextField(blank=False, default=None) price = models.FloatField(blank=False) content_duration = models.DurationField(blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.subject.name i mean i want to load {{section.title }} in one page and {{section.file }} on other when a person click on the {{ section.title }} here is my html <ul> {% for section in section_list %} <div class="card"> <div class="card-header"> {{ subject.name}} </div> <div class="card-body"> <h5 class="card-title">{{ section.title }}</h5> <p class="card-text"></p> <a href="#" class="btn btn-primary">CLick Here</a> </div> </div> {% endfor %} so when a person click on click here a another load up and in that i want to load {{section.file.url}} -
Django form working with bound and unbound form
In django I have the following form for a toy wikipedia website, used when a page is created class WikiSubmitForm(forms.Form): Title = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'placeholder': "Title of wiki page"}), label="") Body = forms.CharField(widget=forms.Textarea(attrs={'placeholder': "Content of wiki page"}), label="") When I allow a user to edit a page, I want to set an input value, so that the initial Body variable in the form is set to the actual content on the page. Confusingly, if I use: form = WikiSubmitForm(initial = {'Title': Title, 'Body': mkdown_file}) The form is created with the preset values, but it looks different to the form as on the create page part of the website, despite them using the same form (see picture at bottom), whereas if I do what I did on the create page but add initial values form = WikiSubmitForm(request.POST, initial = {'Title': Title, 'Body': mkdown_file}) It looks normal, but the initial values don't load. This seems to be because the form is now 'bound'. I found a workaround solution, but out of curiosity was wondering (1) Is there a way to fix the different look of the form when request.POST isn't passed in as an argument (2) Is there a way to pass in … -
Formset Not Saving on UpdateView Django
I'm having problem on formset not saving on UpdateView. This has been discussed in several SO post, and so far I can summarized them to following Make sure to pass an instance. Hence. Reference context['formset'] = journal_entry_formset(self.request.POST, instance=self.object) Override the POST method. Reference Another One My UpdateView is an exact replica of my CreateView except for two changes above. Here is my CreateView: class JournalEntryUpdateView(UpdateView): model = JournalEntry template_name = 'add-journal-entry.html' success_url = reverse_lazy('index') form_class = JournalEntryForm def get_context_data(self, *args, **kwargs): context = super(JournalEntryUpdateView, self).get_context_data(*args, **kwargs) if self.request.POST: context['formset'] = journal_entry_formset(self.request.POST, instance=self.object) else: context['formset'] = journal_entry_formset(instance=self.object) return context def form_valid(self, form): context = self.get_context_data(form=form) formset = context['formset'] if formset.is_valid(): response = super().form_valid(form) formset.instance = self.object formset.save() return response else: return super().form_invalid(form) def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formset = journal_entry_formset(self.request.POST, instance=self.object) print ("form:", form.is_valid() ) # True print ("formset:", formset.is_valid() ) # False print(formset.non_form_errors()) # No Entry print(formset.errors) # {'id': ['This field is required.']} if (form.is_valid() and formset.is_valid()): return self.form_valid(form) else: return self.form_invalid(form) When I click submit, the page just refreshes and nothing happens. (i.e. I don't have that typical yellow error debug screen page). I check the value in the database … -
Django mail sending in very slow
I have implemented a password reset view and it sends a link to an e-mail account. But it takes more time to send. How can I make send faster e-mail using multi-threading class ResetPasswordView(SuccessMessageMixin, PasswordResetView): email_template_name = 'accounts/password_reset_email.html' form_class = CustomPasswordResetForm template_name = 'accounts/password_reset.html' success_message = mark_safe( """<li>We emailed you instructions for setting new password.</li> <br> <li>if an account exists with the email you entered. You should receive them shortly.</li> <br> <li>If you don’t receive an email, please make sure you’ve entered the address you registered with, and check your spam</li> """ ) success_url = reverse_lazy('accounts:reset_password') -
Checkboxes are not the same height as input boxes - Bootstrap
I want the checkboxes on the left side to be the same height as the text input boxes on the right. Not set to proper height HTML: {% block content %} <h1>{{ls.name}}</h1> <form method="post" action="#"> {% csrf_token %} {% for item in ls.item_set.all %} <div class="input-group mb-3"> <div class="input-group-prepend"> <div class="input-group-text"> {% if item.complete == True %} <input type="checkbox", value="clicked", name="c{{item.id}}" checked> {% else %} <input type="checkbox", value="clicked", name="c{{item.id}}"> {% endif %} </div> </div> <input type="text", value="{{item.text}}" class="form-control"> </div> {% endfor %} <div class="input-group mb-3"> <div class="input-group-prepend"> <button type="submit", name = "newItem", value="newItem" class="btn btn-primary">Add Item</button> </div> <input type="text", name="new"> </div> <button type="submit", name = "save", value="save" class="btn btn-primary">Save</button> </form> {% endblock %} -
why do i get `DoesNotExist at /admin/auth/user/2/delete/` error in django
Whenever I try to delete a user from the Django admin panel I get this error: why do I get this error -
Getting List of user's followers in Django Social Media project
In my project I am trying to show a list of other user's followers and following. Right now it only has the requesting user's. Here are my models and views: Models class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) followers = models.ManyToManyField(User, related_name='following', blank=True) Views class FollowersPageView(LoginRequiredMixin, ListView): model = Profile paginate_by = 20 template_name = 'users/followers.html' context_object_name = 'users' def get_queryset(self, **kwargs): return self.request.user.profile.followers.all() class FollowingPageView(LoginRequiredMixin, ListView): model = User paginate_by = 20 template_name = 'users/following.html' context_object_name = 'profiles' def get_queryset(self, **kwargs): return self.request.user.following.all() URLS **(Old url)** re_path(r'^u/followers$', users_views.FollowersPageView.as_view(), name='view_all_followers'), **(New url)** re_path(r'^u/(?P<username>[\w.@+-]+)/followers$', users_views.FollowersPageView.as_view(), name='view_all_followers'), I was trying to change the get_queryset of FollowersPageView to the following but was getting error messages: def get_queryset(self, **kwargs): user_username = self.kwargs['username'] user_followers = Profile.objects.filter(followers=user_username) return user_followers Thank you -
Random <a></a> appeared in HTML code after site went live
Basically my problem is what my question is saying. Before some time we had build a site using Django and it's build in DB. The site had some problems but we fixed the and we got it live. After that we saw a major mistake in the footer where all the three sections where out of place. This was do to a random in the HTML code after we incpect element: This is how the footer is implemented in every page. </body> {% include "main/footer.html" %} </html> Footer code in server <div class="content"> <section> <img class="footer-logo" src="{% static 'material/imgs/logo_banner_inverted.svg' %}" alt="" srcset=""> <!-- <p><i class="fa fa-folder">&nbsp;</i>dummy@gmail.com</p> --> </section> <section class="inline"> <h4 >Our Social Media</h4> <ul class=""> <li class="no-bottom"><a href="https://www.facebook.com/UNSOCLawAUTh"><i class="fa fa-facebook">&nbsp;&nbsp;</i>Facebook</a></li> <li class="no-bottom"><a href="https://www.instagram.com/unsoc.law.auth/"><i class="fa fa-instagram">&nbsp;</i>Instagram</a></li> <li class="no-bottom"><a href="#"><i class="fa fa-linkedin ">&nbsp;</i>Linkedin</a></li> </ul> </section> <section> <h4 >Menu</h4> <ul> <li><a href="{% url 'home' %}"><i class="">&nbsp;</i>Home</a></li> <li><a href="{% url 'about-us' %}"><i class="">&nbsp;</i>About us</a></li> <li><a href="{% url 'contact_form' %}"><i class="">&nbsp;</i>Contact</a></li> </ul> </section> </div> Footer code presented in live site <a> </a><div class="content"><a> <section> <img class="footer-logo" src="/static/material/imgs/logo_banner_inverted.svg" alt="" srcset=""> <!-- <p><i class="fa fa-folder">&nbsp;</i>dummy@gmail.com</p> --> </section> </a><section class="inline"><a> <h4>Our Social Media</h4> </a><ul class=""><a> </a><li class="no-bottom"><a></a><a href="https://www.facebook.com/UNSOCLawAUTh"><i class="fa fa-facebook">&nbsp;&nbsp;</i>Facebook</a></li> <li class="no-bottom"><a href="https://www.instagram.com/unsoc.law.auth/"><i class="fa fa-instagram">&nbsp;</i>Instagram</a></li> <li class="no-bottom"><a … -
access value dynamically in pandas dataframe row pandas()
any help in dynamically accessing pandas() object from a dataframe table in django, not sure where am going wrong, do i need to convert the pandas row into a dict? any help will be much appreciated note: I am using column_dict = {'a':'column A Name', 'b':'Column B Name'} as the columns presented are dynamic and not set template: {% for r in data.itertuples %} <tr> {% for c in columns_dict %} <td>{{ r|lookup:c }}</td> {% endfor %} </tr> {% endfor %} template tags: @register.filter(name='lookup') def lookup(row, key): return row[key] error: tuple indices must be integers or slices, not str r (the pandas row) when printed is in this format: pandas(index=0, a=10, b=20, c=30 .... ) -
Google Drive API in Celery Task is Failing
I am trying using Celery Task to Upload Files to Google Drive once the Files have been Uploaded to Local Web Web Server for Backup. Implementation and Information: Server: Django Development Server (localhost) Celery: Working with RabbitMQ Database: Postgres GoogleDriveAPI: V3 I was able to get credentials and token for accessing drive files and display first ten files,If the quickstart file is run seperately. Google Drive API Quickstart.py Running this Quickstart.py shows files and folder list of drive. So i added the same code with all included imports in tasks.py task name create_upload_folder() to test whether task will work and show list of files. I am running it with a Ajax Call but i keep getting this error. So tracing back show that this above error occured due to: Root of the Error is : [2021-07-13 21:10:03,979: WARNING/MainProcess] [2021-07-13 21:10:04,052: ERROR/MainProcess] Task create_upload_folder[2463ad5b-4c7c-4eba-b862-9417c01e8314] raised unexpected: ServerNotFoundError('Unable to find the server at www.googleapis.com') Traceback (most recent call last): File "f:\repos\vuetransfer\vuenv\lib\site-packages\httplib2\__init__.py", line 1346, in _conn_request conn.connect() File "f:\repos\vuetransfer\vuenv\lib\site-packages\httplib2\__init__.py", line 1136, in connect sock.connect((self.host, self.port)) File "f:\repos\vuetransfer\vuenv\lib\site-packages\eventlet\greenio\base.py", line 257, in connect if socket_connect(fd, address): File "f:\repos\vuetransfer\vuenv\lib\site-packages\eventlet\greenio\base.py", line 40, in socket_connect err = descriptor.connect_ex(address) -
How to add .00 in FloatField of Django?
I did this in my models.py selling_price = models.FloatField() discounted_price = models.FloatField() & my prices are looking like 14,999.0 but i want it to look like 14,999.00 So how can i add that extra zero after decimal ?