Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Doesn't Accept DateTime From DateTimePicker
I'm working on a todo web app and has a user enter an events datetime with a custom bootstrap datetimepicker from here. I have the custom widgets on a form formatted to MM/DD/YY hh:mm A. However, Django doesn't accept the form. A similar question has been asked, but instead of overriding the default DateTimeInput, I would like the form to display in a certain format but be stored in a database in the default format. I'm thinking of using widget tweaks to customize the picker but I don't know how to store it in default formats. What would be the best way to do this? Forms.py from bootstrap_modal_forms.forms import BSModalForm from .widgets import BootstrapDateTimePickerInput from bootstrap_datepicker_plus import DateTimePickerInput from .models import ToDoItem class NewEventForm(BSModalForm): class Meta: model = ToDoItem fields = ['title', 'description', 'start_time', 'end_time', 'remind_time'] widgets = { 'start_time': DateTimePickerInput( options={"format": "MM/DD/YYYY hh:mm A"} ), 'end_time': DateTimePickerInput( options={"format": "MM/DD/YYYY hh:mm A"} ), 'remind_time': DateTimePickerInput( options={"format": "MM/DD/YYYY hh:mm A"} ), } Event form: {% load bootstrap4 %} {% load static %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- Custom Stylesheet --> <link rel="stylesheet" type="text/css" href="{% static 'main/main.css' %}"> <!-- Moment.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" … -
Handling SMS messages when processing forms
I have a few views which handle the forms for new objects being created which seem to lag the user experience due to having to connect to the Twilio API. For example, the following form_valid method sends an SMS message to all receivers of a memo: def form_valid(self, form): form.instance.sender = self.request.user form.save() receiving_groups = form.cleaned_data['receiver'] for group in receiving_groups: username = list( employees.models.Employee.objects.filter( employee_type=group)) for user in username: form.instance.unread.add(user) memo_url = form.instance.pk user.send_sms('memo', memo_url) user.send_email('memo', memo_url) form.save() return super(MemoCreateView, self).form_valid(form) The issue here is that the send_sms method has to wait for a response before continuing. This really makes the site seem slow to the user. I have started to create a request_finished signal but I would have to pass a lot of parameters to the signal so this seems like a bad option. What other options do I have for sending the SMS messages post-success/redirect of the object being created? -
Can I use Sphinx write my help dicumentation in a django project
I have a django project and one menu option is 'Help'. The help documentation is written using Sphinx and there are many pages, e.g. Index, Introduction, First View, Users, Glossary. I have used the html: <li><a href="help" target="_blank">Help</a></li> My urls and views are: urls.py urlpatterns = [ url(r'^help/', views.index, name='index'), ] views.py: def index(request): context = {} url = 'help/index.html' return render(request, url, context) This takes me to the help index page from my menu, but every link I click on in the documentation page re-routes me back through index in views, and re-shows the index page, instead if displaying the link that I requested. If display the index page directly in a browser, without using the django site, it works as expected. I am loathe to integrate the help sub-system into django, because it would get over-written every time I 'make html'. What approach should I take? -
Can't add normal Comment section in my Django web-application
I have trouble with adding comments to my django web-application. I want to add comments to allow users comment posts, like in normal web blog. I've tried a few ways, but nothing worked correctly for me. After a few weeks searching and trying different ways to solve this question, I've stacked on this question. I have some progress, but it's now what I want completely. Now I can only add "comments" from admin panel and it look like this (from admin panel) and like this (from user interface) And I have this issue with padding comments( I don't really understand why it's occurs ¯_(ツ)_/¯ ) Anyway, here is my code, hope someone know how to solve this problem: models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created_date = models.DateField(auto_now_add=True) def __str__(self): return self.text ... class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ManyToManyField('Category', related_name='posts') image = models.ImageField(upload_to='images/', default="images/None/no-img.jpg") slug= models.SlugField(max_length=500, unique=True, null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug}) post_detail.html <article class="media content-section"> {% for comment in post.comments.all %} <ul> {{ comment.text }} {% for reply in comment.replies.all %} <li> … -
Is there a way to add LDAP user and user group management into Django Admin Page?
I am constructing a web application with LDAP Authentication. I have successfully implemented the LDAP authentication, but to manage priviledges on pages I would like to use user base and user group based permission. This whole process managed by the end users so we need a panel/page to view all LDAP users and user groups (which we already filtered in settings.py) Settings.py: .... #Include DB Routers DATABASE_ROUTERS = ['ldapdb.router.Router', ] # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True ################################################################### ################# LDAP AUTHENTICATION SETTINGS #################### ################################################################### # Baseline configuration. AUTH_LDAP_SERVER_URI = "ldap://10.xx.xx.x7" AUTH_LDAP_BIND_DN = "CN=s****1,OU=Generic Accounts,DC=xxx,DC=local" AUTH_LDAP_BIND_PASSWORD = "*****" AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_USER_SEARCH = LDAPSearch( "OU=xxxAddressList,DC=xxx,DC=local", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_USER_FLAGS = { "is_active": AUTH_LDAP_USER_SEARCH, "is_staff": AUTH_LDAP_USER_SEARCH, "is_superuser": AUTH_LDAP_USER_SEARCH, } # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "username":"cn", "first_name": "givenName", "last_name": "sn", "email": "mail", } # Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "OU=xxxAddressList,DC=xxx,DC=local", ldap.SCOPE_SUBTREE, "(objectClass=organizationalPerson)", ) #I HAVE TRIED THESE LINES BUT NO OBJECT APPEARED ON DJANGO ADMIN … -
How to render file in django template
PLease I am trying to render django file in the template, the problem is that , I am taking audio, video and images as input and I don't know how to render them in my html template. Whether I will use tag or tag or tag. -
Display custom success or error progress bar
I am making a django app that displays a progress bar. So far I have got it working to display a progress bar using this library and the following code which they suggested. <div class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;">&nbsp;</div> </div> <div id="progress-bar-message">Waiting for progress to start...</div> <script src="{% static 'celery_progress/celery_progress.js' %}"></script> <script> // vanilla JS version document.addEventListener("DOMContentLoaded", function () { var progressUrl = "{% try: url 'celery_progress:task_status' task_id catch: pprint("PHEW") %}"; CeleryProgressBar.initProgressBar(progressUrl); }); </script> However, how might i integrate the above code with the code below to get it to display success or error: function customSuccess(progressBarElement, progressBarMessageElement) { progressBarElement.innerHTML = ( '<figure class="image"><img src="/static/projects/images/aww-yeah.jpg"></figure>' ) progressBarElement.style.backgroundColor = '#fff'; progressBarMessageElement.innerHTML = 'success!' } function customError(progressBarElement, progressBarMessageElement) { progressBarElement.innerHTML = ( '<figure class="image"><img src="/static/projects/images/okay-guy.jpg"></figure>' ) progressBarElement.style.backgroundColor = '#fff'; progressBarMessageElement.innerHTML = 'shucks.' } CeleryProgressBar.initProgressBar(taskUrl, { onSuccess: customSuccess, onError: customError, }); -
How can I omit time at HTML {{ post.published_date }} tag?
How can I omit time at HTML {{ post.published_date }} tag? I use Python and Django, I tried showing the published date, but I don't want to display time. <!--html file--> <a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }} ... &nbsp {{ post.published_date }}</a> e.g. what I have: This is post title ... Nov. 19, 2019 p.m. 5:37 This is post title, too! ... Nov. 24, 2019 a.m. 2:30 what I want: This is post title ... nov. 19, 2019 This is post title, too! ... nov. 24, 2019 -
How to document django channels websocket api
I am trying to make restful API with django rest framework, i am documenting this api with default django rest framework documentation and it is working fine. But i have also two another non rest endpoints. Django eventstream endpoint for SSE events. I send here information about any changes on the server that affect the user or things with which he is associated with anything. Django channels websocket endpoint for in-app chat over users. chat also supports several commands and has few complex options. So, my question is, how to document this two endpoints? My favourite option is including this endpoints to my existing docs but i don't know how to do this without loosing its readability. Is there some good practices for documenting websocket/eventstream api in python? Or another good standard/app/html generotor which i can include and serve in my django app? Thanks for Your help -
timezone() missing required argument 'offset' (pos 1) in models.py while trying to migrate, what is the reason?
while making a blog, my models.py: from django.db import models class Post(models.Model): title=models.CharField(max_length=200,blank=True) author=models.ForeignKey('auth.user',on_delete=models.CASCADE,) image=models.ImageField(upload_to='media/',blank=True) content=models.CharField(max_length=1000,blank=True) date=models.DateTimeField(auto_now_add=False, editable=False) tag=models.CharField(max_length=100,blank=True) slug=models.CharField(max_length=200,blank=True) def __str__(self): return self.title when i run python manage.py makemigrations, datefield is created in database: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0013_auto_20191124_1448'), ] operations = [ migrations.AlterField( model_name='post', name='date', field=models.DateTimeField(editable=False), ), ] but when i try to run python manage.py migrate, it shows the following error: (Django-k7xSBAPV) C:\Myfiles\python\Django\myblog\blog_project>python manage.py makemigrations No changes detected (Django-k7xSBAPV) C:\.....\blog_project>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions Running migrations: Applying blog.0004_post_date...Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site- packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site- packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site- packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site- packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site- packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site- packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site- packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site- packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\ronyrocks\.virtualenvs\Django-k7xSBAPV\lib\site- packages\django\db\migrations\executor.py", … -
Showing javascript or html within html tabs
I am making a django app. The following are bits and pieces from my index.html template. I have code that displays a progress bar: <div class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;">&nbsp;</div> </div> <div id="progress-bar-message">Waiting for progress to start...</div> <script src="{% static 'celery_progress/celery_progress.js' %}"></script> <script> // vanilla JS version document.addEventListener("DOMContentLoaded", function () { var progressUrl = "{% try: url 'celery_progress:task_status' task_id catch: pprint("PHEW") %}"; CeleryProgressBar.initProgressBar(progressUrl); }); </script> I have: {{index | safe}} that displays an error message should my progress fails. I also have the following code for displaying tabs: <div class="tab"> <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen$ <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button> <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button> </div> <div id="London" class="tabcontent"> <h3>London</h3> </div> <div id="Paris" class="tabcontent"> <h3>Paris</h3> <p>Paris is the capital of France.</p> </div> <div id="Tokyo" class="tabcontent"> <h3>Tokyo</h3> <p>Tokyo is the capital of Japan.</p> </div> function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } // Get the element with id="defaultOpen" and click on it document.getElementById("defaultOpen").click(); </script> How might I modify … -
i want to atttch 3 images wiht 1 image when i access 1 image come all 3 images with this in django
image = models.ImageField(upload_to='images/') attach 3 images with this image but this images take from user input form and access 3 images with one images and automatically maintain a database table to save this images -
How to change django Response behavior to not nest data in "data" field
I would like to change how an endpoint is sending a Response Whenever I use django response like this: return Response(serializer.data, status=status.HTTP_200_OK) Model I use: class StationModel(models.Model): class Meta: db_table = 'station' id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) shortname = models.CharField(max_length=20) lat = models.DecimalField(max_digits=50, decimal_places=15) lan = models.DecimalField(max_digits=50, decimal_places=15) The response i get from an endpoint looks like this: { "data": [ { "type": "Mymodel", "id": "1", "attributes": { "name": "xxxxx", "shortname": "xxxxx", "lat": "123.000000000000000", "lan": "213.000000000000000" } } Is it possible to customize response to look like this, or at least get rid of "data" field: { "id": "1", "name": "xxxxx", "shortname": "xxxxx", "lat": "123.000000000000000", "lan": "213.000000000000000" } -
How to get multiple models in ModelUpdateForm (Django-bootstrap-modal-form plugin)
i'm trying to get values from multiple models in my UpdateForm. Case: Im clicking on my 'edit' button in template and calling in urls.py path('update/<int:pk>', views.ModelUpdateView.as_view(), name='update_model'), than in views.py class ModelUpdateView(BSModalUpdateView, PopRequestMixin, CreateUpdateAjaxMixin): model = Model3D form_class = ModelUpdateForm template_name = 'update_model.html' success_message = 'Modell wurde erfolgreich bearbeitet.' success_url = reverse_lazy(index) which is calling in forms.py class ModelUpdateForm(BSModalForm): class Meta: model = Settings fields = ['extruder_Temperature', 'heatbed_Temperature', 'build_Plate_Adhesion', 'layer_Height', 'infill_density', 'print_Speed', 'nozzle_size', 'material', 'extrusion_Rate'] But i need to get additional models in forms.py like model= Settings, Model3D, Pictures etc. to call in fieldsfor example 'name','id','pictures',... -
How to log every request and response if 500 error occurs in django rest framework?
I am using django for rest APIs. I do have a logging code in settings.py. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(asctime)s %(levelname)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(asctime)s %(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/tmp/OAuthLog_Production.log', 'formatter': 'simple' }, }, 'loggers': { 'oauth': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, } }, } In the views.py it is being used like this whenever any exception occurs. import logging logger = logging.getLogger("oauth") except Exception as ex: logger.exception(ex) response = helper.generateStandardResponse(ResponseCodes.exception_in_finding_user, "Exception in finding user", data, False); logger.info("get_profile_details : Exception in finding user") return Response(response, status=status.HTTP_200_OK) Since, I am using Elastic beanstalk to host the application I am not returning 500 status code. I am returning custom responses. Even after this there are few 500 errors returned by application. And those are causing environment to "Degrade". I checked my log file but it has errors like this. 2019-11-23 23:53:10,600 ERROR UserProfile matching query does not exist. Traceback (most recent call last): File "/opt/python/current/app/profiles/views.py", line 514, in get_profile_details user_profile_detail = UserProfile.objects.get(mobile1=mobile, account_type=account_type) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/models/query.py", line 385, in … -
Custom Template Tag Render Method Receiving Request Context Instead of Context
This book - https://github.com/PacktPublishing/Django-2-Web-Development-Cookbook-Third-Edition - provides a number of useful custom template tags (except I can't get each to work for the same reason). For example here is the 'try_to_include' custom template tag - class IncludeNode(template.Node): def __init__(self, template_name): self.template_name = template.Variable(template_name) def render(self, context): try: # Loading the template and rendering it included_template = self.template_name.resolve(context) if isinstance(included_template, str): included_template = get_template(included_template) rendered_template = included_template.render(context) except (template.TemplateDoesNotExist, template.VariableDoesNotExist, AttributeError): rendered_template = "" return rendered_template @register.tag def try_to_include(parser, token): """ Usage: {% try_to_include "sometemplate.html" %} This will fail silently if the template doesn't exist. If it does exist, it will be rendered with the current context. """ try: tag_name, template_name = token.split_contents() except ValueError: tag_name = token.contents.split()[0] raise template.TemplateSyntaxError( f"{tag_name} tag requires a single argument") return IncludeNode(template_name) The line - rendered_template = included_template.render(context) throws the error - context must be a dict rather than RequestContext So naturally I checked the django docs - https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/#writing-the-renderer Where it doesn't really mention the 'context' parameter. But it seems obvious enough - at least you'd have thought: the 'context' object is the context passed to the template. Indeed later on at section - https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/#setting-a-variable-in-the-context - it gives the example of adding a variable to the … -
'ManyToOneRel' object has no attribute 'verbose_name' error after searching
I have an app where I created a relation between Offer and the Contractor in the Offer model: contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE) Everything works fine except one thing. When I am trying to search through Contractors model using verbose name, I am receiving an Atributeerror: 'ManyToOneRel' object has no attribute 'verbose_name' Searching code below (contractors/views.py): def get(self,request): contractors = self.model.objects.all() if 'search' in request.GET: search_for = request.GET['search'] if search_for is not '': filter = request.GET['filterSelect'] search_in = [field.name for field in Contractor._meta.get_fields() if field.verbose_name==filter] kwargs = {'{0}__{1}'.format(search_in[0], 'contains'): search_for} contractors = self.model.objects.all().filter(**kwargs) Why Am I receiving and error if searching is performed on Constructor model and Constructor model have no fields related to Offer model? How can I fix that? Or how to create searching bar where user can choose where to search from drop down list containing all verbose names of the model fields? -
Django middleware get dynamic url param value
path('<int:id>/', views.client), I have a middleware and I need to get from url. I have try to put inside of __call__(self, request, id), but its not working. anyone know how to achieve this class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request, id): <---error from django.http import HttpResponse return HttpResponse('before middleware' + id) <----error response = self.get_response(request) from django.http import HttpResponse return HttpResponse('after middleware') return response -
How to filter out objects and only show ones where the user is in a ManyToMany field associated with the object Django
So I have this system where my Post object has a ManyToMany field and it's called Saves. So like for example on Reddit you can save a post. So I got it working and users can save posts, and it adds them to the ManyToMany field. However, I want to filter out these posts and only show the posts where said user is in the ManyToMany field. Here is my models.py class Post(models.Model): author = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) saves = models.ManyToManyField(User,blank=True,related_name='post_saves') I have the saves field connected to the User model Django provides. And here is my views.py class PostSaveRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): pk = self.kwargs.get("pk") slug = self.kwargs.get("slug") obj = get_object_or_404(Post,pk=pk,slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated: if user in obj.saves.all(): obj.saves.remove(user) else: obj.saves.add(user) return url_ So this is all working fine, it adds the user to the ManyToMany field, but now I want to know how I can filter out posts and only display ones where the user is in the ManyToMany field. Here is my saved posts view. class PostSaveListView(ListView): model = Post template_name = 'mainapp/post_saved.html' paginate_by = 10 queryset = models.Post.objects.all() def get(self,request): posts = Post.objects.all() return render(request, self.template_name) def get_queryset(self): return Post.objects.filter().order_by('-published_date') So with Post.objects.all(), how … -
Django redirection malfunctioning behind a load balancer
I have to deploy my Django based app behind a load-balancer that I can't control. E.g https://example.com/loadbalancer/django/. It means all requests targeted to that url (and subsequent additional ones) will be diverted to my Django app. So I worked on the urls.py main file to add a variable named URL_PREFIX = "loadbalancer/django/" : from django.conf import settings from django.contrib import admin from django.urls import include, path, re_path from django.views.generic import TemplateView from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), re_path(r"^api-auth/", include("rest_framework.urls")), re_path(r"^accounts/", include("allauth.urls")), path("", TemplateView.as_view(template_name="landing.html"), name="landing"), ] if settings.URL_PREFIX: urlpatterns = [path(r"{}".format(settings.URL_PREFIX), include(urlpatterns))] So far I deployed the application using Nginx, Supervisor and Gunicorn. Everything works perfectly except when I try to use the confirmation dialog for django-allauth. When the user clicks on the link for confirming his signup e-mail e.g: https://example.com/loadbalancer/django/accounts/confirm-email/MQ:1iYsGH:_O-2PyGzd_FiqrpP-2HvI-pmy2s/ , the form generate a new url https://example.com/loadbalancer/django/accounts/confirm-email/MQ:1iYsGH:_O-2PyGzd_FiqrpP-2HvI-pmy2s/loadbalancer/django/beaver/accounts/login/ where the form try to send data. And that produce an error. What solution would you advise me to take ? I have tried to use an adapter : from django.conf import settings from allauth.account.adapter import DefaultAccountAdapter from decouple import config class BeaverAdapter(DefaultAccountAdapter): def get_email_confirmation_redirect_url(self, request): path = config("URL_PREFIX", default="/giews/food-prices/beaver/") + "accounts/login/" return path But it hasn't worked so … -
How to add auto increment in postgreSQL?
I am new to PostgreSQL. I was trying to create a table and tried to add a primary key and auto increment in same column and came up with an ERROR ERROR: syntax error at or near "SERIAL" LINE 2: upID int SERIAL primary key Below is my Query create table tblIK( upID int SERIAL primary key, upName varchar(100) NOT NULL, upMin varchar(100) NOT NULL, upMax varchar(100) NOT NULL, upYEAR Date NOT NULL, upMi varchar(100)NOT NULL, upIK varchar(100)NOT NULL ) -
how to implement tinymce in django form
Iam making blog app in django and trying to add blog using template and i have implemented front end view as the tinymce text area is showing but on the submission of django form its not being submit so please kindly help , and tell me how can i add blog content using tinyMCE the form is not submitting when iam trying to submit it doesn't do any action enter image description here My template {% extends 'index-base.html' %} {% load static %} {% block content %} <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"> </script> <center> <h1>ADD BLOG</h1> <form method="POST" action="{% url 'blog:createblog' %}" enctype="multipart/form-data"> {% csrf_token %} {{creationform}} <button type="submit">Add</button> </form> </center> <script> tinymce.init({ selector: 'textarea', plugins: 'print preview fullpage paste importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap quickbars emoticons', imagetools_cors_hosts: ['picsum.photos'], menubar: 'file edit view insert format tools table help', toolbar: 'undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | forecolor backcolor removeformat | pagebreak | charmap emoticons | fullscreen preview save print | … -
AWS Elastic Beanstalk deploy error, PermissionError: [Errno 13] Permission denied
I'd like to ask you a question. I've created an app server with Django and now it's working well in the local. I want to deploy to AWS Elastic Beanstalk, and the server works well until I specify environment variables after eb create. container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" leader_only: True 02_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" 03_wsgireplace: command: "cp .ebextensions/wsgi.conf ../wsgi.conf" at .extensions/10_python. eb deploy after entering contact_commands as shown in the code, the server stops working If I check the server log, I will see PermissionError as shown below, but I don't understand what the problem is. If you know how to solve this problem, I'd really appreciate it. File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 674, in exec_module File "<frozen importlib._bootstrap_external>", line 780, in get_code File "<frozen importlib._bootstrap_external>", line 832, in get_data PermissionError: [Errno 13] Permission denied: '/opt/python/current/app/balance10_server/common/urls.py' -
Templating in Django
I am new to Django development and stuck over a issue. From views.py I am sending one list return render(request, 'InsertPage/About.html' , {'list1': list1}) and want to able to perform operations on this list in the html page. Eg list contains 6 items, 3 index per product. I wish to create operations like get the length of the list divide it by 3 and the quotient would be the number of products. And using the same variable (no of products) I was planning to make a for loop to create bootstrap cols and dynamically load the data to the html page. here is the html code - {% for i in list1 %} <h1> {{ k }} </h1> {% endfor %} Would really appreciate the help, also open for suggestions if there is a better way to achieve what i am trying to do. -
How to get author and text from textarea python django? (without javascript)
I should get text from textarea and save code and author this is a link of project https://github.com/AggressiveGhost/python_contester.git I would be grateful if you help solve the problem. thanks in advance