Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to require password on django allauth social login with google workspace
The basic question is how to go about requiring a user to put in their password when using google SSO. We have a few users who use the same device and don't want them to all be able to log in as each other. If I could require a password after a unit of time that would be okay, but I think I have set in workspace to require login after 12 hours already. Otherwise logging in with google works fine. It's just requiring some kind of re-authentication periodically that we need. Here is the basic setup on django SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } Have tried updating the login link to use action-reauthenticate {% provider_login_url 'google' action="reauthenticate" %} This forces the user to select their account but doesn't require a password. -
'ProgrammingError: column does not exist' in Django
I've been moving development of my website over to using Docker. I replaced sqlite as my database with postgresql then ran the command docker-compose exec web python manage.py migrate in my Docker environment. I also updated MEDIA ROOT and MEDIA settings in my settings.py file and updated mysite/urls.py. When I go to 127.0.0.1:8000/admin to the look at stored/uploaded files I get an error: Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (column human_requirementschat.alias does not exist LINE 1: SELECT "human_requirementschat"."id", "human_requirementscha... ^ ) was the direct cause of the following exception: File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/admin/options.py", line 688, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/contrib/admin/options.py", line 2065, in changelist_view "selection_note": _("0 of %(cnt)s … -
Django form.is_valid() is incorrectly returning false for a missing field
When I submit a form to update a task in my project, the is_valid function returns false, and on the page it says: Error! Please correct the following errors: Description: This field is required. But when I print the POST request into the console, the description field isn't required, and it does have data. this is the views.py function: def task_edit(request, task_id, slug): """ Display an individual task for editing. """ # Retrieve the task instance task = get_object_or_404(Task, pk=task_id) # Retrieve the job instance job = get_object_or_404(Job, slug=slug) if request.method == "POST": # Print out the request.POST dictionary to inspect the data print(request.POST) # Initialize form with task instance and data from request add_task_form = AddTaskForm(data=request.POST, instance=task) if add_task_form.is_valid(): # Save the form data to the task instance task = add_task_form.save(commit=False) task.job = job task.save() messages.success(request, 'Task Updated!') return HttpResponseRedirect(reverse('job_detail', args=[slug])) else: messages.error(request, 'Error updating task!') else: # Initialize form with task instance add_task_form = AddTaskForm(instance=task) and this is the JS function: // Handle click event for edit button $(".edit-button").on("click", function() { console.log("Edit Task button clicked"); var taskId = $(this).data("task_id"); var description = $(this).data("description"); var tradesRequired = $(this).data("trades-required"); var tradesmanAssigned = $(this).data("tradesman-assigned"); var timeRequired = $(this).data("time-required"); var isCompleted = … -
Django querying tables without id - Multi-Database
In this example I have created (https://github.com/axilaris/docker-django-react-celery-redis/), I have implemented multi-database accessing a Postgresdb table that does not have "id" column. (you can find out in the project code /backend/simple/models.py Referring to my gist (https://gist.github.com/axilaris/123516cdc9023dc02ebac3cba6644dd7), when accessing the model, it prints the error: django.db.utils.ProgrammingError: column simpletable.id does not exist LINE 1: SELECT "simpletable"."id", "simpletable"."name", "simpletabl... here is the definition of the table: Is there a way to handle this table in Django (as I'm interested to use ORM) without creating a new column id or views. Can I do something within Django to support this table ? -
Django get all users with last_login older than 360 days
I'm trying the below code ... from datetime import datetime, timedelta from django.utils import timezone yearago = timezone.make_aware(datetime.today() - timedelta(days=366)) old_users = User.objects.filter(last_login__gt=yearago) old_users.all The output show users that have logged in this year, whereas I want users who's last login was over 366 days ago. So what am I missing? -
render_to_string can't access to a context correctly
I want to use weasyprint to transform a html template to PDF. I'm using Django 5.0. Here is a part of my template (The template works fine, Django renders it correctly): <div> <h1>Tu Pedido está listo, {{request.user.username}}!</h1> </div> <h4>Pedido ID: {{pedido}}</h3> <div class="container text-center" > <table class="table"> <thead class="thead-dark"> <tr> <th>Producto</th> <th>Cantidad</th> <th>Precio</th> </tr> </thead> <tbody> {% for key, producto in carro.items %} <tr> <td> {{producto.nombre}} </td> <td> {{producto.cantidad}} </td> <td> $: {{producto.precio}} </td> </tr> {% endfor %} <tr> <td colspan="3">Total: $: {{total}}</td> </tr> </tbody> </table> </div> <div class="container text-center"> <a href="{% url 'home' %}" class="btn btn-outline-primary me-2">Volver</a> <!--pdf--> <form id="pdf_form" method="post" action="{% url 'generar_pdf' %}" style="display: none;"> {% csrf_token %} <input type="hidden" name="pedido" value="{{ pedido }}"> <input type="hidden" name="carro" value="{{ carro }}"> <input type="hidden" name="total" value="{{ total }}"> </form> <button id="pdf_button" class="btn btn-primary" type="submit">Descargar pdf</button> </div> <!-- send form --> <script> document.getElementById("pdf_button").addEventListener("click", function() { document.getElementById("pdf_form").submit(); }); </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> And here is my views.py: def generar_pdf(request): if request.method == "POST": pedido = request.POST.get("pedido") carro_info = request.POST.get("carro") total_compra = request.POST.get("total") # if I print these 3 variables, the values are ok #--- here is the problem ---# html_string = render_to_string( template_name='exito.html', context={"pedido": pedido, "carro":carro_info, "total": total_compra}, request=request) #------# … -
redirect to the django project
good afternoon, there was a problem when creating the project. the situation is as follows, the built-in view logout does not work correctly. when I log out of the project on the site page on behalf of the user, I will be redirected to http://127.0.0.1:8000/users/logout /. moreover, everything is working properly in another project. below are the variables from the settings file, urls and the button template: urls.py from django.contrib.auth.views import LoginView, LogoutView from django.urls import path from users.apps import UsersConfig from users.views import RegisterView, ProfileView app_name = UsersConfig.name urlpatterns = [ path('', LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', LogoutView.as_view(next_page='users:login'), name='logout'), path('register/', RegisterView.as_view(), name='register'), path('profile/', ProfileView.as_view(), name='profile'), ] settings.py AUTH_USER_MODEL = 'users.User' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' template <div class="col-sm-4 offset-md-1 py-4"> <h4 class="text-white">Меню</h4> <ul class="list-unstyled"> <li><a href="{% url 'catalog:home' %}" class="text-white">Главная</a></li> <li><a href="{% url 'catalog:contact' %}" class="text-white">Контакты</a></li> <li><a href="{% url 'blog:blog' %}" class="text-white">Блог</a></li> {% if user.is_authenticated %} <li><a href="{% url 'users:logout' %}" class="text-white">Выйти</a></li> <li><a href="{% url 'users:profile' %}" class="text-white">Профиль</a></li> {% else %} <li><a href="{% url 'users:login' %}" class="text-white">Войти</a></li> <li><a href="{% url 'users:register' %}" class="text-white">Регистрация</a></li> {% endif %} </ul> </div> redirect to the main page -
Django Real time chart when database was updated by MQTT
my Django server receive data from device over MQTT sucessfully. def on_message(mqtt_client, userdata, msg): from lorawan_api.server_processing import SERVER_PROCESSING print(f'Received message on topic: {msg.topic}') # with payload: {msg.payload}') data_processing = SERVER_PROCESSING() data_processing.data_stored(msg.topic,msg.payload) Now i want to display them in real time chart. I found some solution using AsyncWebsocketConsumer. Is that the best way to display real time chart -
Django template, Need 2 values to unpack in for loop; got 1
Been facing issues regarding the error above. I am trying to highlight words based on an ID given by the dictionary in Django <td class="text-center"> {% with background_color=None %} {% for key, value in row.Context.items %} {% if not background_color %} {% for pattern, color in pos_color_map.items %} {% if pattern in value|default:''|lower %} {% with background_color=color %} {% endwith %} {% endif %} {% endfor %} {% endif %} {% endfor %} <span style="background-color: {{ background_color }}"> {{ key }} </span>{% if not forloop.last %}, {% endif %} {% endwith %} </td> -
Why is my Celery configuration not taking effect?
I'm running a Django app with Celery 5.3.4. I'm using Redis as the broker. I want to configure the task_time_limit and task_time_soft_limit options, but I can't get them to take effect when running locally. I've tried setting them very low, and running a slow task that sleeps for 10 seconds: app.conf.task_time_limit = 5 app.conf.task_soft_time_limit = 1 But, when running the Celery worker locally, it completes the slow task and doesn't time out: 2024-03-05T15:46:04.647630Z [info ] Task slow_task[97f51f79-ac48-4aa3-9098-a3ec5a299adc] received [celery.worker.strategy] 2024-03-05T15:46:14.741217Z [info ] Task slow_task[97f51f79-ac48-4aa3-9098-a3ec5a299adc] succeeded in 10.093100208323449s: None [celery.app.trace] I've tried configuring Celery in many different ways. Here's my current config, spread out over 2 files: celery.py: import os from celery import Celery from celery.signals import worker_init from django.conf import settings # Set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kosa_api.settings") app = Celery("kosa_api") # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django apps. app.autodiscover_tasks() app.conf.task_time_limit = 5 app.conf.task_soft_time_limit = 1 settings/celery.py (this is imported in my app's settings): from kosa_api.settings.utils import get_safe_redis_url … -
How to create new database table looping through another model in Django
I have a Thermocouple model and I want to create a different model to record Temperatures for each Thermocouple created and save it to database. for thermocouple | Id | name | | 1 | thermocouple_1 | | 2 | thermocouple_2 | | 3 | thermocouple_3 | then TemperatureRecord should be as | id | date | time | user | thermocouple_1 | thermocouple_2 | thermocouple_3 | | 1 | March 5, 2024 | 2:48 p.m. | 1 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 | | 2 | March 5, 2024 | 2:52 p.m. | 2 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 | | 3 | March 5, 2024 | 2:55 p.m. | 1 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 | Thermocouple model class Thermocouple(models.Model): name = models.CharField(max_length=50, unique=True, help_text="Name of the thermocouple") def __str__(self): return f"{self.name}" class Meta: ordering = ['id'] @classmethod def bulk_create_from_import(cls, data): cls.objects.bulk_create([cls(**item) for item in data]) and i want to create a different database table model named TemperatureRecord consisting id,user,date,time and Thermocouple items. if created 10 thermocouple, need to be 10 column for each Thermocouple to record temperatures (IntegerField) I tried using the following code but didn't work. class TemperatureRecord(models.Model): date = models.DateField() time = … -
hello please help friends solve my problem
[[enter image description here](https://i.stack.imgur.com/3sQfS.png)](https://i.stack.imgur.com/YYUKG.png) tell me how to solve this problem I have already tried everything, nothing helped, if anyone knows how to solve this, I will be grateful for the day I can’t figure out how to fix this error wewewewewewewewewewewe -
I want to create a waybill for my customers who ordered from my website with aramex
the problem that show every time to me in this image it says there is problem with date format this is the code i use: import datetime def send_issue_policy(request): url = "https://ws.sbx.aramex.net/ShippingAPI.V2/Shipping/Service_1_0.svc/json/CreateShipments" headers = { "Content-Type": "application/json", "Accept": "application/json" } payload = { "ClientInfo": { "UserName": "testingapi@aramex.com", "Password": "R123456789$r", "Version": "v1", "AccountNumber": "4004636", "AccountPin": "432432", "AccountEntity": "RUH", "AccountCountryCode": "SA", "Source": 24 }, "Shipments": [ { "Reference1": "", "Reference2": "", "Reference3": "", "Shipper": { "Reference1": "TEst mutli label", "Reference2": "", "AccountNumber": "4004636", "PartyAddress": { "Line1": "Test TEST", "Line2": "", "Line3": "", "City": "riyadh", "StateOrProvinceCode": "", "PostCode": "", "CountryCode": "sa", "Longitude": 0, "Latitude": 0, "BuildingNumber": "null", "BuildingName": "null", "Floor": "null", "Apartment": "null", "POBox": "null", "Description": "null" }, "Contact": { "Department": "", "PersonName": "aramex", "Title": "", "CompanyName": "aramex", "PhoneNumber1": "966512345678", "PhoneNumber1Ext": "", "PhoneNumber2": "", "PhoneNumber2Ext": "", "FaxNumber": "", "CellPhone": "966512345678", "EmailAddress": "test@test.com", "Type": "" } }, "Consignee": { "Reference1": "", "Reference2": "", "AccountNumber": "71500004", "PartyAddress": { "Line1": "Test", "Line2": "", "Line3": "", "City": "riyadh", "StateOrProvinceCode": "", "PostCode": "", "CountryCode": "sa", "Longitude": 0, "Latitude": 0, "BuildingNumber": "", "BuildingName": "", "Floor": "", "Apartment": "", "POBox": "null", "Description": "" }, "Contact": { "Department": "", "PersonName": "aramex", "Title": "", "CompanyName": "aramex", "PhoneNumber1": "966512345678", "PhoneNumber1Ext": "", "PhoneNumber2": "", … -
HTML page is not displaying properly
Here, I extends the base.html to cart.html and then I block the content and end that block at the end of the code. But after I run the code the navbar is not displaying properly and the cart appears to right side of the page. Please help me to fix this issue. Codes on cart.html {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title> Responsive Registration Form | CodingLab </title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.0/font/bootstrap-icons.css"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="js/script.js" type="text/javascript"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style media="screen"> body{ background: #ddd; min-height: 100vh; vertical-align: middle; display: flex; font-family: sans-serif; font-size: 0.8rem; font-weight: bold; } .title{ margin-bottom: 5vh; } .card{ margin: auto; max-width: 950px; width: 90%; box-shadow: 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 1rem; border: transparent; } @media(max-width:767px){ .card{ margin: 3vh auto; } } .cart{ background-color: #fff; padding: 4vh 5vh; border-bottom-left-radius: 1rem; border-top-left-radius: 1rem; } @media(max-width:767px){ .cart{ padding: 4vh; border-bottom-left-radius: unset; border-top-right-radius: 1rem; } } .summary{ background-color: #ddd; border-top-right-radius: 1rem; border-bottom-right-radius: 1rem; padding: 4vh; color: rgb(65, 65, 65); } @media(max-width:767px){ .summary{ border-top-right-radius: unset; border-bottom-left-radius: 1rem; } } .summary .col-2{ padding: 0; } … -
display information using django tags
I am writing a site on Django, the purpose of this site is to create a test to assess students' knowledge I need help with outputting options for answers to a question I keep the questions in a list and the answer options in a nested list for example: questions = [ "question1","question2","question3"] answers = [[ "answer1","answer2",answer3 ],["answer1","answer2",answer3,answer4 ] , ["answer1","answer2",answer3 ]]` and I need this data to be displayed in the following format: question1 answer1 answer2 answer3 question2 answer1 answer2 answer3 answer4 question3 answer1 answer2 answer3 here is my code, it does not work very correctly, I know, I have not yet figured out how to implement it in Django tags {% for question in questions %} {{question}} {% for answer in answers %} {% for current in answer %} {{ current }} {% endfor %} {% endfor %} {% endfor %} -
Django: Create form from items in model, where each item in the model has multiple associated questions
I want to ask users multiple questions for each of a list of items in a Django model. As an illustrative example: Suppose I'm collecting data on people's opinions of the Harry Potter films. I want to know if someone has a) watched one of the films, and b) what rating (out of 10) they give said film. Assume that my Django app contains 3 models: Films - to populate the list of films; Users - details on the person who has responded; Reponses - responses for each user. This contains three columns: UserID, FilmID, Rating. It is only populated when a user has given a score for a film (i.e., no blank ratings) The table below shows what kind of answer I'd want to receive: a check of whether they watched the film, and their rating out of 10. Film Watched? Rating HP-1 Y 8 HP-2 Y 9 HP-3 N - HP-4 N - HP-5 N - HP-6 Y 7 HP-7 N - HP-8 N - The HTML of the form would have a similar layout: film name, check box for if it has been watched, and the rating field (dropdown or integer field). This would then load the … -
Can my heroku app store images even after restarting dyno
I have 2 services, backend api on django and frontend on react. My goal is to make django admin page create new food models with pasting new image. On local host everything works fine,images are saving on media/food_images and even after restarting local host they stay there. But when I host them on heroku, make few food models and then restart dyno images dissapear. I checked that when I make new food models in "heroku run bash" there is no media folder. Is there a way to save them for ever? -
How to use count() to get items between specific dates
With this code I am able to get all orders items that is related to Article but here is the problem, I want to get the number of orders that are between two dates that are between the assigned timestamp.How can I do it? class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='ordersauthor') article = models.ForeignKey(Article, null=True, blank=True, on_delete=models.CASCADE,related_name='ordersarticle') timestamp = models.DateTimeField(auto_now_add=True) total_price = models.FloatField(default='0', validators=[MaxValueValidator(99999999999999999999)]) class ArticleSerializer(serializers.ModelSerializer): orders = serializers.SerializerMethodField(read_only=True) class Meta: model = Article fields = '__all__' def get_orders(self, language): return language.ordersarticle.count() Initial Output: { "id": "2f95f593-6b95-45aa-97c4-e4157eed5189", "timestamp": "2024-03-04T16:55:42.572529Z", "orders": 4, // All orders }, Expected Output: { "id": "2f95f593-6b95-45aa-97c4-e4157eed5189", "timestamp": "2024-03-04T16:55:42.572529Z", "orders": 1, // Orders between 4th and 7th of march (Example) }, -
Retrieve selected Select Option value
I tried to retrieve the selected unit_selector data for the key, value in for loop in the value_row class. but it didn't work. It just didn't display anything. {% if forloop.first %} <tr class="title_row"> {% for k,v,i,z,b in sorted_title_list %} {% if k == selected_item %} {% if b|length == 1 %} {% else %} <th><label for="**unit_selector**"> <select class="master_select" id="**unit_selector**" name="unit_selector"> {% for key, value in b.items %} <option value="{{ value }}" id="{{ key }}">{{ value }}</option> {% endfor %} </select> </label></th> {% endif %} {% endif %} {% endfor %} </tr> {% endif %} <tr class="**value_row **{% if epoch_form.errors %}error{% endif %}"> {% for k,v,i,z,b in sorted_title_list %} {% if k == selected_item %} {% if b|length == 1 %} {% else %} {% for key, value in b.items %} {% if unit_selector.key == key %} <td class="_unit" id="{{ key }}">{{ value }}</td> {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </tr> -
Django backend with celery workers - memory threshold
I have a system with some periodic tasks. Each periodic task reads in files and creates objects out of them in the RAM. To prevent data loss, the cached file content is immediately stored from the peridoic task into the database after creating the object out of it. Then the file is deleted from the source. The object is queued into a RabbitMQ and the Celery workers take them for further processing and concurrency. Before caching the next file, the memory usage of the system is fetched with psutil. If it exceeds a threshld, the periodic task stops to read in files and continues with it, when executed the next time. My question is If this is generally a feasible approach if no data must be lost (the files are either stored in the database or still in the source folder) If it is a good approach to keep the synchronisation effort low (files are deleted after reading, the worker operates on objects and does not delete files and there is no sync needed with the periodic task) Which memory threshold is "safe" and fast enough. The file size can be up to 40 MB. -
Signup & Login not working in production in DigitalOcean using DjangoRestFramework and getting server error 500
-I followed the DigitalOcean Documentation to upload my Django app to digitalOcean: https://docs.digitalocean.com/developer-center/deploy-a-django-app-on-app-platform/ And I served my static files and media files using DigitalOcean space and all is good and I can make all of my requests in production but Login & Sign up is only working in my local machine but not in DigitalOcean Server I'm getting server error 500 this is my configuration : settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key()) # set debug to false by default DEBUG = os.getenv("DEBUG", "False") == "True" ALLOWED_HOSTS = os.getenv( "DJANGO_ALLOWED_HOSTS", "www.aklalatshop.com,https://akalat-shopcsphu.ondigitalocean.app").split(",") # Application definition INSTALLED_APPS = [ # 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'egystoreapp', # For generating / getting access token 'oauth2_provider', 'social_django', ######################################## 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', # for social login 'rest_framework_social_oauth2', # for digitalOcean space 'storages', 'bootstrap4', 'rest_framework', 'rest_framework.authtoken', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'egystores.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'egystores.wsgi.application' DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True" if DEVELOPMENT_MODE is True: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", … -
Best way to update multiple templates based on form submission?
I'm working on a project that does several calculations based on user input, and I am now trying to create a new form in my variables_input template where the user can retrieve the values used in prior runs, and this works on the variables_input template resulting with the values being displayed on the page. However when the user goes to another page the values displayed are the most recently run calculations. How do I make it so when the user chooses a past run that they don't have to run the calculations but just get the values from the appropriate models to be displayed on the appropriate page? I was wondering if signals could achieve the desired result or if a simpler solution is possible. Below is an example of my project's code. variables_input.html {% block content %} <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" , value="Submit" name="prior_run"> </form> <form action="" method="post"> <h2>Variables Table One</h2> {% csrf_token %} <!-- Table Columns --> <table> <table class="vartable" style="text-align: center;"> <colgroup> <col class="grey"> </colgroup> <thead> <tr> <th>Variable 1</th> <th>Variable 2</th> <th>Variable 3</th> <th>Variable 4</th> <th>Run Name</th> <th></th> </tr> </thead> <tbody> <tr> <div> <td><input type="text" value="{{inputs_list.0}}" name="var_one"></td> <td><input type="text" value="{{inputs_list.1}}" … -
encountering so many errors during web application deployment in firebase
I have successfully deployed my django web application into firebase. But when I did run the hosturl the website I deployed was only able to display html content and images but couldn't display the content as I registered it should in css,js, bootsrap files.it completely could not access these files but it could access the image files which present in the same directory which is static which is within public directory.which is default directory created by firebase during firebase init process.Could you help me in solving this error.or atleast let me know what error could it be. i deployed web application in firebase to host it.for this i put my html file in public directory which basically created by firebase itself during firebase initialization.and i put static files like js,img,css,bootstrap in static directoru which is within the public directory.and the error after the deployement when i did run the hosturl it did not display the website properly means it did nto display as i registered ti should be in js,css,bootstrap files.becoz it could not access that files whereas ti could access the image files which are in same directory where js,css,bootstrap files does exist. -
AttributeError at /login/ 'AnonymousUser' object has no attribute '_meta'
im trying to create my own costume view for the login page and im getting the following error. this is my views: def my_view(request): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) login(request, user) return reverse_lazy('HomeView') this is the urls: urlpatterns = [ path('', HomeView.as_view(), name='HomeView'), path('show_todo_list/<int:pk>', ShowToDoView.as_view(), name='Show_To_Do_list'), path('create_task/', CreateTaskView.as_view(), name='Create_Task'), path('change_task/<int:pk>', ChangeTaskView.as_view(), name= 'Change_Task'), path('delete_task/<int:pk>', DeleteTaskView.as_view(), name= 'Delete_Task'), path('login/', my_view, name='login') ] and the error is in line 34: login(request, user) AttributeError: 'AnonymousUser' object has no attribute '_meta' -
MySQLdb.OperationalError: and django.db.utils.OperationalError 1054, "Unknown column" after field rename in Django and MySql
I have django app that is connected to MySql database. I have renamed the field in models.py and succesfuly ran the migration. (the name alteration is written in migrations file) I have also manually altered the field in the MySql, so it's called the same as in models.py (let's say it's called 'newName'); After trying to run new migrations i get MySQLdb.OperationalError: and django.db.utils.OperationalError1054, "Unknown column 'oldName' in 'mysql_tableName'" What should I do? Why does django db connection have oldName of the field? inspectdb shows the new field name in the output; when checking mysql, there is new name of the field, running the sql command in db (SELECT oldName FROM mysql_tableName) works fine.