Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign <User: username> must be a "User" instance
I'm trying to create a web gallery in Django, but I'm stuck right at the beginning. I can't assign the user ID as a foreign key in the database. views.py file from django.shortcuts import render, redirect from django.template.context_processors import csrf from .forms import RegistrationForm, LoginForm, ImageForm from django.contrib import messages from django.contrib.auth import authenticate, login, get_user_model from django.contrib.auth import views as auth_views from django.contrib.auth.decorators import login_required from .forms import ImageForm @login_required def add_image_view(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = form.save(commit=False) if request.user.is_authenticated: user_obj = get_user_model().objects.get(id=request.user.id) print(user_obj) #I receive the expected value.[marek] print(user_obj.id) #I receive the expected value.[2] print(user_obj.username) #I receive the expected value.[marek] image.username = user_obj image.save() return redirect('user_panel') else: form = ImageForm() return render(request, 'main/add_image.html', {'form': form}) models.py files from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(blank=True) class Meta: verbose_name = 'użytkownik' verbose_name_plural = 'użytkownicy' ordering = ['username'] permissions = [('special_permission', 'Specjalne uprawnienie')] groups = models.ManyToManyField( 'auth.Group', related_name='main_users', # zmianiona nazwa odwrotnego dostępu blank=True, verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_query_name='main_user' ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='main_users', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', … -
How to pass in the context data from model in Django
I'm in view (View1) with model1 and i want pass something through context to template. I have a problem because I want to pass data from another model and I don't know how to refer to it: class View1(): model = model1 def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) context_data['mycontext'] = # i want to pass data from model3_field1 model1: class model1(): some_fields.. model2: class model2(): model2_field1 = models.ForeignKey(model1, on_delete=models.CASCADE, null=True, blank=True) model2_field2 = models.ForeignKey(model3, on_delete=models.SET_NULL, null=True, blank=True) model3: class model3() model3_field1 = models.CharField(default=YesNo.NO, max_length=4, blank=True, choices=YesNo.choices) -
Django template render speed issue for large queryset
I have completed a web application for work and was doing some various tests. One of the tests was for a "exaggerated" number of items on a given page and how long it would take to load (the page is basically a dashboard for a helpdesk system) . My results are quite bad with the test page taking some 20 to 25 seconds for 1200 items on a standard spec system and 3 - 10s on a very high spec system. I dont ever expect the active calls to reach that number on the dashboard but am looking at a worst case scenario. I have also tried with pagination, but I am probably implementing it wrong as going to the next page seems to rerun the queries and takes the same time as displaying all 1200 items irrespective of whether I am displaying 1 item or 10. As the project is quite large and contains sensitive information, I cant really provide the code here for reproducible results but I created another basic project that basically highlights what I am experiencing. It can be downloaded here: https://drive.google.com/drive/folders/19yvzHugC7hjcVJpiHeYiEjyX-SA2_wu3?usp=sharing This code is not that bad as not many attributes are referenced in the … -
Handle NoSuchKey error with Custom Storage class AWS S3 and Django
I am using Django, I wanted to handle the NoSuchKey error which happens when am redirected to the file link from my Django project. How best can I use the Custom storage error to handle this : """Custom storage settings.""" from storages.backends.s3boto3 import S3Boto3Storage from botocore.exceptions import NoSuchKey from django.shortcuts import render class FileStorage(S3Boto3Storage): """File storage class.""" print(" Hi there am AWS") def open(self, name, mode='rb'): try: return super().open(name, mode) except NoSuchKey: return {'errror': 'Error Happened'} I already defined the class in the settings.py as below : DEFAULT_FILE_STORAGE = 'proj.storage.FileStorage' Remember when you define the following env variables, you can auto upload files to the specific Images or File fields in the Models, now I want a centralized way of handling the NoSuchKey error and I show a custom page or template AWS_LOCATION = ENV.str('AWS_LOCATION', default='') AWS_ACCESS_KEY_ID = ENV.str('AWS_ACCESS_KEY_ID', default='') AWS_SECRET_ACCESS_KEY = ENV.str('AWS_SECRET_ACCESS_KEY', default='') AWS_S3_REGION_NAME = ENV.str('AWS_S3_REGION_NAME', default='') AWS_S3_SIGNATURE_VERSION = ENV.str('AWS_S3_SIGNATURE_VERSION', default='') AWS_S3_FILE_OVERWRITE = ENV.bool('AWS_S3_FILE_OVERWRITE', default=False) How can I do this ? -
Django not bringing pk to template
I am at the moment practicing my Django-Skills and I am learning a language, so I thought I could combine these two learning paths: I have a models.py class Word(models.Model): English = models.CharField(max_length=50) German = models.CharField(max_length=50) Bahasa_Indonesia = models.CharField(max_length=50) and a class based view, which returns the word-list with a specified language: class WordListByLanguageView(View): '''outputs all the words in a selected language as a list. The link to the detail forwards to word-detail. ''' def get(self, request, language): words = Word.objects.all().values(language) # retrieves only the language field return render(request, 'word_list.html', {'words': words, 'language': language}) I want users to pick which language they want to learn on their dashboard: {% block content %} <h1>User Dashboard</h1> <form method="post" action="{% url 'user-dashboard' %}"> {% csrf_token %} <label for="language">Start learning </label> <select name="language" id="language"> <option value="English">English</option> <option value="German">German</option> <option value="Bahasa_Indonesia">Bahasa Indonesia</option> <!-- Add more language options as needed --> </select> <button type="submit">Start Learning</button> </form> {% endblock %} class UserDashboardView(View): def get(self, request): # Render the user dashboard template return render(request, 'user_dashboard.html') def post(self, request): # Get the selected language from the form submission language = request.POST.get('language') # Redirect to the word list URL with the selected language as a parameter return redirect('word-list-language', language=language) The … -
Vscode extension suggestion not working on some folders
When I tried to create a HTML file inside my django project folder (appfolder/templat/test/page.html) it's not suggesting any tags when I type. But same time it's working on html files that are outside those folder it works perfectly Now I'm creating html file outside and paste it to that folder . How can I solve this ?? -
Firefox can’t establish a connection to the server in django channels echo server
I wrote an echo server with Django Channels, which I will give you the link channels_echo_server When I try to connect to Echo Server, I get this error in the console Firefox can’t establish a connection to the server at ws://127.0.0.1:8000/ws/ Socket closed unexpectedly I get the same error in the Chrome browser I uninstalled and reinstalled Channels and even the Django project several times But it didn't work where is the problem from? -
Django concurrent requests
I'm using Django as a framework, but I'm encountering an issue with concurrent requests. The application consistently responds to (n-1) requests and handles the last one, but it fails to send a response to the end user. I'm seeking assistance to resolve this problem. Can anyone help me with this? -
apache reverse proxy with django authentication and geoserver
i want to use django authentication before redirectiong to geoserver using apache reverse-proxy, i can Redirect to login page but after submitting the /login/?next=/geoserver return me to first page not to geoserver i tried a lot of configuratin but now success: <VirtualHost *:9443> ServerName localhost ProxyPreserveHost On # Proxy requests for GeoServer to Django ProxyPass /geoserver http://localhost:8080/geoserver ProxyPassReverse /geoserver http://localhost:8080/geoserver ProxyPassReverseCookiePath /geoserver / # Redirect /geoserver requests to Django authentication <Location /geoserver> Redirect /geoserver /login/?next=/geoserver </Location> # Proxy all other requests to Django ProxyPass / http://localhost:8000/ ProxyPassReverse / http://localhost:8000/ -
Django - Celery - How to handle complex tasks
Following problem needs to get solved: In my Django project I have to collect, manipulate and save specific data on regular basis. Example: Every minute I have to retrieve data from a heating-system via REST-API and process them Every minute I have to retieve data from a PV-inverter via REST-API and process them Every six hours I have to retrieve data from an external data provider and do some processing on it. After midnight I have to do some calculation on data from previous day ... and more to come in future From my perspective the Django/Celery/Beat approach would fit for above scenarios. I'm aware it's not a real message-based use case - more a batch processing use case to not setup cronjobs. In my Django project I have created apps (for the specific subsystems) and some general packages on project level. Described scenarios can be called (from Python shell and via Bash script outside development via cronjob. Now I tried to use Celery Beat to orchestrate above scenarios. But I'm not able to call the scripts from inside the celery tasks. Simply nothing happens - I guess importing all packages and scripts fail. I worked with several tutorials to … -
Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE
I'm trying to debug url.py in my project but i got this error all the time, I tried almost everything, any ideas? Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Agents of Faust streaming stop event consumption after some days
I have an application using faust-streaming. The application has around 20 agents each consuming events from different Kafka topics. The problem is, after several day, the agents stop consuming and I have to restart application container. Here is an example agent: @app.agent(event_sent_topic, concurrency=20) async def send_event_agent(stream): """""" task_name = asyncio.current_task().get_name() interface = Interface() async for records in stream.take(10, 1): for record in records: send_event_tasks_queue[record.user_id].append(task_name) await _wrap_send_event(record=record, interface=interface) await asyncio.sleep(0) # Skipping current event loop run for giving execution chance to other tasks. Container logs now only contains some warnings like below: * m_consumer.m_agent -----> ============================================================ ['Stack for <coroutine object movie_updated_agent at 0x7f303428bce0> (most recent call last):\n File "/project/m_consumer/movie_updated_consumer.py", line 22, in movie_updated_agent\n async for records in stream.take(faust_config.max_stream_take, 1):\n File "async_generator_asend", line -1, in [rest of traceback truncated]\n'] * z_consumer.retry_send_product_agent -----> ============================================================ ['Stack for <coroutine object retry_send_product_agent at 0x7f30341506b0> (most recent call last):\n File "/project/z_consumer/retry_consumer.py", line 29, in retry_send_product_agent\n async for records in stream.take(faust_config.max_stream_take, 1):\n File "async_generator_asend", line -1, in [rest of traceback truncated]\n', 'Stack for <coroutine object retry_send_product_agent at 0x7f303428bf00> (most recent call last):\n File "/project/z_consumer/retry_consumer.py", line 29, in retry_send_product_agent\n async for records in stream.take(faust_config.max_stream_take, 1):\n File "async_generator_asend", line -1, in [rest of traceback truncated]\n', 'Stack for <coroutine object retry_send_product_agent … -
How to pass a Django object from template to view by POST request?
I trying to pass the value of a checkbox to my views.py in the following way: my_template.html <input type="checkbox" name="playlist" value='{{ playlist }}'> views.py json_str_list = request.POST.getlist('playlist') The serialized JSON in json_str_list looks like this: '{\'id\': \'UUkfDws3roWo1GaA3pZUzfIQ\', \'title\': "Item 1", \'created_on\': datetime.datetime(2023, 6, 12, 20, 44, 41, 392273, tzinfo=datetime.timezone.utc)}' This seems not to be a valid JSON string. Can I adjust the way how Django serializes the object? I want to deserialize the JSON back to an object with json.loads() and get following error Expecting property name enclosed in double quotes -
Django signals post_save method
I am creating API for online-store with django-rest-framework and can't get my post_save signal working for some reason. The idea is: I have a model Product and Category. Product model has a field named in_stock, which is True by default. As for model Category, it also has field in_stock, but here it is False. When the product instance created, I want assign Category field in_stock to True value using singals. Here is the code of models: class Category(models.Model): category_name = models.CharField(max_length=255, verbose_name='Категория') description = models.TextField(verbose_name='Описание') in_stock = models.BooleanField(default=False, verbose_name='В наличии') slug = models.SlugField() image_url = models.ImageField(upload_to='categories/uploads/%Y/%m/%d/', null=True, blank=True, default='media/images.png', verbose_name='Изображение') parent = models.ForeignKey('self', on_delete=models.PROTECT, related_name='children', null=True, blank=True, verbose_name='Родительская категория') def __str__(self): return f'{self.parent}, {self.category_name}' class Product(models.Model): product_name = models.CharField(max_length=255, verbose_name='Товар') description = models.TextField(verbose_name='Описание') price = models.IntegerField(verbose_name='Цена') discount_percent = models.IntegerField(default=0, verbose_name='Процент скидки') in_stock = models.BooleanField(default=True, verbose_name='В наличии') amount = models.IntegerField(verbose_name='Количество') vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, verbose_name='Поставщик') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, verbose_name='Бренд') image = models.ForeignKey(ProductImage, on_delete=models.SET_DEFAULT, default=1, verbose_name='Изображение') Here is signals: @receiver(post_save, sender=Product) def update_category_is_active(sender, instance, created, **kwargs): print(instance) if created and instance.in_stock: instance.category.in_stock = True instance.category.save() -
django annotate add key inside child object
I am fetching blogs with author as fetch_related, i want to add new key inside author but working but adding 'qq' in blog object is working but i want to add keys inside author like isAuthorFollowing, isAuthorBlocked, but i am not able to add any key inside author object this is the error i am getting Cannot resolve keyword 'new_key' into field. post_query = Blog.objects.select_related( 'author').annotate(qq=Value(1), author__new_field=Value(1)).get(filters) post_serializer = blogsSerializers.PostUserSerializer2( post_query, context={'request': request, 'user': user}) class PostUserSerializer2(serializers.ModelSerializer): author = usersSerializers.BlogPostAuthorDataSerializer2(read_only=True,) qq = serializers.IntegerField() class Meta: model = Blog fields = ('id', 'title', 'slug', 'created_at', 'updated_at' 'author', 'topic', 'poster_size', 'description', 'content_count', 'content','qq') class BlogPostAuthorDataSerializer2(serializers.ModelSerializer): new_field = serializers.IntegerField() class Meta: model = User fields = ['id', 'username', 'full_name', 'new_field'] -
How can i start a django project?
So in command prompt i did python -m django-admin startproject mysite And i got this error while trying with env: C:\Users\DR\Desktop\ChatMat\env\Scripts\python.exe: No module named django-admin First i tried without a env same error and when i tried with env still same error Here is the error without env: C:\Users\DR\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe: No module named django-admin Im trying to make a django project but the command prompt command is not working Anyone got a solution for this? -
TypeError: 'NoneType' object is not callable (DjangoAdmin)
I am trying to register one of my Models in the Django admin page (code below): class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey( 'Product', on_delete=models.SET_NULL, null=True, related_name='+') def __str__(self): return self.title class Meta: ordering = ['title'] code from admin.py: @admin.site.register(models.Collection) class CollectionAdmin(admin.ModelAdmin): list_display = ['title', 'products_count'] def products_count(self, collection): return collection.products_count def get_queryset(self, request): return super().get_queryset(request).annotate(products_count=Count) But I get this error for the collection Model for some reason and for no other model that i registered. Traceback: C:\Users\jonas_6xnnk8f\PycharmProjects\storefront\store\admin.py changed, reloading. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\threading.py", line 980, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\contrib\admin\__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "C:\Users\jonas_6xnnk8f\PycharmProjects\djangoproject\venv\lib\site-packages\django\utils\module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "C:\Program Files (x86)\Microsoft … -
filling in an html template from ModelForm
Hello Everyone. I need to fill out a template using ModelForm by fields with a drop-down list. I know that the form can be filled out as {{form.as_p}}. But is it possible to fill it out without using {{form.as_p }}? And how to do it? The way I'm trying to do it is highlighted in the template. I understand that there is a lot of text, but I really need your help, do not pass by :) model.py class Product(models.Model): name = models.CharField(max_length=40) def __str__(self): ` return self.name`` class Variety(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Tender(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) variety = models.ForeignKey(Variety, on_delete=models.CASCADE) price = models.DecimalField(max_digits=4, decimal_places=2,) delivery_date = models.DateField(default=date.today) category = models.ForeignKey(Category, on_delete=models.CASCADE) delivery_basis = models.CharField(max_length=3, choices=[('CPT', 'CPT')]) payments = models.CharField(max_length=20, choices=[('Наличный расчет', 'Наличный расчет')]) comment = models.TextField(max_length=4000, blank=True, default='Комментарий отсутствует.') def __str__(self): return self.product forms.py class AddTenderForm(forms.ModelForm): class Meta: model = Tender fields = '__all__' views.py def index(request): form = AddTenderForm() if request.method == 'POST': form = AddTenderForm(request.POST) if form.is_valid(): form.save() return redirect('add') return render(request, 'fmtender/form_for_adding_a_tender.html', {'form': form}) part of the template (for convenience) <div class="col-12"> <label for="id_product" class="form-label">Продукт</label> <select class="form-select" … -
Issue creating relational tables for Django models with django-taggit and django-treebeard
I am trying to create hierarchical tags for my Django blog project using django-taggit and django-treebeard. However, I am encountering issues with the creation of the relational tables. Here is my models.py file: from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from taggit.models import TagBase, ItemBase from taggit.managers import TaggableManager from treebeard.mp_tree import MP_Node class Tag(TagBase, MP_Node): name = models.CharField(max_length=10, unique=True) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) node_order_by = ['name'] class TaggedPost(ItemBase): post = models.ForeignKey('Post', on_delete=models.CASCADE) tag = models.ForeignKey('Tag', related_name="tagged_posts", on_delete=models.CASCADE) class Meta: unique_together = ('post', 'tag') def __str__(self): return self.tag.name class Post(ItemBase): title = models.CharField(max_length=125, unique=True) slug_title = models.SlugField(max_length=255, unique=True) summary = models.TextField(max_length=100) body = models.TextField() published_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=True) tags = TaggableManager(through='TaggedPost') class Meta: ordering = ['-published_date'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug_title = slugify(self.title) super(Post, self).save(*args, **kwargs) I ran python manage.py makemigrations and python manage.py migrate successfully, but the relational tables (blog_tag and blog_taggedpost) are not being created. When I try to create a new tag using Tag.objects.create(name='Parent Tag'), I receive the following error: django.db.utils.ProgrammingError: relation "blog_tag" does not exist I am not sure why the tables are not being created and how to … -
Django form, dynamic number of fields based on another field
The following is my Django model for different type of questions: class Question(models.Model): QUESTION_TYPES = [ ('SBA', 'Single Best Answer (MCQ)'), ('EMQ', 'Extended Matching (Matching)'), ('SAQ', 'Short Answer Question'), ] question_type = models.CharField(max_length=3, choices=QUESTION_TYPES) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) option = models.TextField(default="Option") class Subquestion(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) subquestion = models.TextField(default="subquestion") I need a form to create new questions with all relevant fields. The fields needed on the form are dynamically decided based on a field in Question model. If question type if SBA is chosen, there should be 5 options fields (no subquestions) appearing and saving to the related models. If EMQ is chosen there should be 5 subquestions, and 7 options fields appearing. if SAQ is chosen no subquestions and options should appear. I tried using formsets but due to poorly written tutorials I could not understand. As the changes in question type should instantly change the remaining field, I am interesting in dynamic form fields. Any one can help? -
base.css does not apply in Django project
I have a following structure of my folders: And I try to import the base.css to base.html so that it applies everywhere: MY HTML: <!DOCTYPE html> {% load static %} <html> <head> <link rel="stylesheet" href="{% static 'base.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> (...) </html> MY SETTINGS: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') Tried different combinations, but nothing seems to work. Please help :) -
How i can create query in django
I have the following model: class PointsforUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(null=True, default=0) slug = models.SlugField(max_length=255, blank=True, unique=True) class RunningTasks(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) fixed = models.BooleanField(default=False) slug = models.SlugField(verbose_name='URL', max_length=255, blank=True, unique=True) task = models.ForeignKey(Task, on_delete=models.CASCADE) points = models.IntegerField(null=True, default=0) class TaskCreateForm(forms.ModelForm): class Meta: model = RunningTasks fields = ('task',) class RunTaskCreateUserView(LoginRequiredMixin,CreateView): model = RunningTasks template_name = 'usersboard/tasks_create.html' form_class = TaskCreateForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context How can I create a task for a user where `pointsforuser.points = task.points? -
¿como puedo soluciona Error en el deploy de railway?
hola Estoy haciendo una api en django y trato de hacer el deploy en railway pero me sale un error enter image description here asi tengo el archivo requirements.txt contourpy==1.0.7 cycler==0.11.0 distlib==0.3.6 Django==4.2.2 djangorestframework==3.14.0 filelock==3.12.2 fonttools==4.39.4 kiwisolver==1.4.4 matplotlib==3.7.1 mpmath==1.3.0 mysqlclient==2.1.1 numpy==1.22.4 packaging==23.1 pandas==1.4.2 Pillow==9.5.0 platformdirs==3.5.3 PyMySQL==1.0.3 pyparsing==3.0.9 python-dateutil==2.8.2 pytz==2022.1 six==1.16.0 sqlparse==0.4.4 sympy==1.12 typing_extensions==4.6.3 tzdata==2023.3 virtualenv==20.23.0 ``` en procfile web: python manage.py migrate && gunicorn ap_Softseguros.wsgi -
How to let user pick date AND time in the form?
I am trying to create a sort of To Do List. Majority of it is done. I can get user to enter the task, along with its detail and pick the starting and ending date. However, since I am rendering the fields in a form, I want the user to easily and conveniently enter the date and time. For that I have added a datepicker type widget. The datetime stored in database is still in ISO format. Now, the issue is that user can pick or enter the date perfectly fine. But it does not allow the user to enter the time. Once the date has been picked, the user can't enter the time. The code goes as under: class TaskForm(ModelForm): class Meta: model = TaskModel exclude = ["completed"] widgets = { 'title': TextInput(attrs={"class": "form-control"} ), 'detail': Textarea(attrs={"class": "form-control"}), 'start_time': DateInput(format = ['%d/%m/%Y %H:%M'], attrs={"type":"date", 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker1'}), 'end_time': DateInput(format = ['%d/%m/%Y %H:%M'], attrs={"type": "date", 'class': 'form-control datetimepicker-input'}) } And the Model.py file is: class TaskModel(models.Model): title = models.CharField(max_length=30) detail = models.TextField(blank=True) start_time = models.DateTimeField() end_time = models.DateTimeField() completed = models.BooleanField(blank = True, null=True) The rest of the code is just simple and conventional Django based views and … -
Changing localhost to a custom domain name in Django
I have modified my ALLOWED_HOSTS variable to include "localhost", "127.0.0.1", and "mysite.com". Additionally, I have created a hosts file in the same directory as my manage.py file which contains the following line: 127.0.0.1 mysite.com Despite these changes, the localhost name does not appear to be updating.