Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images is not rendering even after giving the correct directory path in Django. but works when I give incomplete directory
So I have the image that I want to display in my page in a subdirectory 'media'.So I wrote this in my settings.py as recommended everywhere in the internet and documentation: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') And when I load the page I get this error: Not Found: /media/media/slider-1.jpg [09/May/2023 19:31:11] "GET /media/media/slider-1.jpg HTTP/1.1" 404 3943 why the path is media/media in my terminal eventhough the MEDIA_ROOT has only one 'media/' So I just wrote: MEDIA_ROOT = os.path.join(BASE_DIR) and this worked perfectly eventhough the image is not inside the base directory but inside the subdirectory called 'media' I'm curious how is this happening. -
How to remove title of inline object in django admin UI
As you can see in the image ,there is an image, there is one 1st model (1st mentioned in image), 2nd model is inlined one. Just wanted to remove the 2nd model title(which is highlighted by red color, complete row I want to delete class NewmodelInline(admin.StackedInline): fields = ['field1', 'field2', 'field3'] extra = 1 model = Newmodel @admin.register(Test) class AuthorAdmin(admin.ModelAdmin): delete_cache_keys_for_model = 'Test' fieldsets = ( (None, { 'fields': ( 'name', 'age', 'lastmod', ), }), ('Numbers', { 'fields': ( 'test1', 'test2', ), }), ) form = TestForm inline_type = 'stacked' inlines = [NewmodelInline] with the help of above code generated a form attached in the image. Now just wanted to remove the title from the admin UI, as attached in image(whole row highlighted with red color and text as 2nd) -
Django admin searchfield with GenericForeignKey
My Django Foo model has the following GenericForeignKey: content_type = models.ForeignKey(ContentType, blank=True, null=True, on_delete=models.SET_NULL) object_id = models.PositiveIntegerField(blank=True, null=True) my_object = GenericForeignKey('content_type', 'object_id') my_objects can be instances of Baz and (rarely) Qux models. The Qux model has a foreign key to Baz. I want to have a searchfield in my Foo admin page that would search by baz_id and yield either instances of Foo that have the Baz of the given ID in my_object field or instances of Foo that have Qux related to the Baz of the given ID. Here's what I'm trying to do: class FooAdmin(...): # some custom classes and mixins here, neither of which overrides get_search_results() query_fields_placeholders = {'object_id': 'Baz ID'} ... ... search_fields = ('object_id',) def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) if search_term: baz_content_type = ContentType.objects.get_for_model(Baz) qux_content_type = ContentType.objects.get_for_model(Qux) baz_queryset = queryset.filter( content_type=baz_content_type, object_id=search_term ) related_qux_ids = Subscription.objects.filter(baz_id=search_term).values_list( 'id', flat=True ) qux_queryset = queryset.filter( content_type=qux_content_type, object_id__in=related_qux_ids ) queryset = baz_queryset | qux_queryset return queryset, use_distinct However, what happens is that only Foo instances that have Baz instances as my_objects are returned by the search and those that have Qux instances in my_object fields seem completely ignored (as if the qux_queryset part … -
How can i call an object?
I have got a project with auntification. This is my models.py: class Profile(models.Model): profile_id = models.IntegerField(primary_key=True) last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) photo_url = models.URLField() There is a views.py: @login_required def home(request): return render(request, 'home.html') def vk_callback(request): try: vk_user = UserSocialAuth.objects.get(provider='vk-oauth2', user=request.user) vk_profile = vk_user.extra_data user_info = UserInfoGetter(vk_profile['access_token']) pers_id, first_name, last_name, photo_url = user_info.get_vk_info() try: user_profile = Profile.objects.get(profile_id=pers_id) except Profile.DoesNotExist: user_profile = Profile.objects.create( profile_id=pers_id, first_name=first_name, last_name=last_name, photo_url=photo_url ) user_profile.first_name = first_name user_profile.last_name = last_name user_profile.photo_url = photo_url user_profile.save() except UserSocialAuth.DoesNotExist: pass return redirect(home) I need to take pers_id in order to pull out the values of photo, name, last_name in home. How can I do this? -
Error while Dockerizing a simple Django app? (Beginner here)
I'm trying to dockerize my django app whilst following a tutorial, and of course nothing goes as planned hahah. Could you help me understand what's going on and how do i fix it? This is what i did: 1) I made my dockerfile ` `FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt RUN pip install psycopg2-binary COPY . . CMD python manage.py runserver 0.0.0.0:80` ` 2) i ran "docker build -t app ." which worked 3) i ran "docker run -p 8888:80 app" but thats when the following issue popped up: 1) I made my dockerfile 2) i ran "docker build -t app ." which worked 3) i ran "docker run -p 8888:80 app" but thats when the issue popped up Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, … -
Unable to test a celery chain when tasks are executed by different celery apps
I have two celery apps in my environment that are : app1 = Celery('app1', broker=BROKER_URL1, backend=BROKER_URL1) app2 = Celery('app2', broker=BROKER_URL2, backend=BROKER_URL2) From a Django app within a web container I need to call a chain of tasks: task1 is executed by app1 task2 is executed by app2 The two apps have different virtual environments / python versions so there no way of executing both tasks by the same app. @app1.task(bind=False) def task1(): return {"key": "value"} @app2.task(bind=False) def task2(result): return result["key"] task_chain = ( app1.signature('app1.task1') | app2.signature('app2.task2') ) I am then trying to test the chain works correctly - task1 appears to execute correctly but task2 errors: @override_settings(CELERY_TASK_ALWAYS_EAGER=True) def test_chain(self): task_chain.apply_async().get() # Error: celery.exceptions.NotRegistered: 'app2.task2' How can i test this chain? -
JWT How to mock JWT token authentication?
I'm writing unit tests in Django where I have to mock JWT token validation. I used the following code but it throws exception. I suspect the issue is because I'm unable to use decode method because jwt.encode returns a str value which does not have decode method. But in the sample I came across, jwt.encode returns bytes. helper def generate_jwt_token(): client_secret = getattr(settings, "AUTH0_CLIENT_SECRET", None) payload = {'user_id': 1} token = jwt.encode(payload, client_secret, algorithm='HS256') #Commenting the following line because jwt.encode returns str and str does not #have decode method #return token.decode('utf-8') return token Unit test @patch('jwt.decode') def test_post_request_with_valid_data_succeeds(self, mock_decode): payload1 = {'user_id': 1} mock_decode.return_value = payload1 response = self.client.post(self.url, self.dataset, format="multipart", HTTP_AUTHORIZATION=f'Bearer {self.token}') Exception Traceback (most recent call last): File "/usr/local/lib/python3.8/unittest/mock.py", line 1325, in patched return func(*newargs, **newkeywargs) File "/app/apps/datasets/test/test_views.py", line 89, in test_post_request_with_valid_data_succeeds response = self.client.post(self.url, self.dataset, format="multipart", HTTP_AUTHORIZATION=f'Bearer {self.token}') File "/root/.local/lib/python3.8/site-packages/rest_framework/test.py", line 296, in post response = super().post( File "/root/.local/lib/python3.8/site-packages/rest_framework/test.py", line 210, in post return self.generic('POST', path, data, content_type, **extra) File "/root/.local/lib/python3.8/site-packages/rest_framework/test.py", line 234, in generic return super().generic( File "/root/.local/lib/python3.8/site-packages/django/test/client.py", line 473, in generic return self.request(**r) File "/root/.local/lib/python3.8/site-packages/rest_framework/test.py", line 286, in request return super().request(**kwargs) File "/root/.local/lib/python3.8/site-packages/rest_framework/test.py", line 238, in request request = super().request(**kwargs) File "/root/.local/lib/python3.8/site-packages/django/test/client.py", line 719, in … -
Django ORM: This queryset contains a reference to an outer query and may only be used in a subquery
In the queryset, I want to get the average of what subquery returns and then group by 'store_id' and 'avg_sales'. However, when I used the following queries: subquery = StoreStatistics.objects.filter( store=OuterRef("store_id"), products__in=products, # list of ids created_date__gte='2023-01-01', ).annotate( month=TruncMonth("created_date") ).values( "month", "store" ).annotate( avg_sales_per_month=Avg("quantity") ) queryset = Company.objects.filter( company_id=company_id ).annotate( avg_sales=Subquery(subquery.aggregate(Avg("avg_sales_per_month"))) ).values( "store_id", "avg_sales" ) I got the following error: This queryset contains a reference to an outer query and may only be used in a subquery. Can anyone tell where am I making a mistake? -
Django migration error (SQL to PostgreSQL): return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable
I created a dump.json file from my SQL local DB. After that, I uploaded my file to the server prepared for PostgreSQL and I caught the following error after using the following commands: python3 manage.py shell >>> from django.contrib.contenttypes.models import ContentType >>> ContentType.objects.all().delete() >>> quit() python manage.py loaddata dump.json My error: Traceback (most recent call last): File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "posts_group" does not exist LINE 1: UPDATE "posts_group" SET "title" = 'Котики', "slug" = 'cats'... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/farexzon/hw05_final/yatube/manage.py", line 21, in <module> main() File "/home/farexzon/hw05_final/yatube/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/commands/loaddata.py", line 114, in loaddata self.load_label(fixture_label) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/management/commands/loaddata.py", line 181, in load_label obj.save(using=self.using) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/core/serializers/base.py", line 223, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/db/models/base.py", line 780, in save_base updated = self._save_table( File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/db/models/base.py", line 853, in _save_table updated = self._do_update(base_qs, using, pk_val, values, update_fields, File "/home/farexzon/hw05_final/venv/lib/python3.10/site-packages/django/db/models/base.py", … -
NoReverseMatch at /detail/3/
I have multiple todo lists, and each todo list has list items. There is a completed field in the list item model. I get this error in the detail page when I put a form to handle if the list item has been completed by the logged in user. The error I get is: NoReverseMatch at /detail/3/ Reverse for 'completed_list_item' with arguments '('', '')' not found. 1 pattern(s) tried: ['completed\\-item/(?P<list_pk>[0-9]+)/(?P<item_pk>[0-9]+)/\\Z'] Request Method: GET Request URL: http://127.0.0.1:8000/detail/3/ Django Version: 4.1.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'completed_list_item' with arguments '('', '')' not found. 1 pattern(s) tried: ['completed\\-item/(?P<list_pk>[0-9]+)/(?P<item_pk>[0-9]+)/\\Z'] Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix Raised during: List.views.detail The traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/detail/3/ Django Version: 4.1.4 Python Version: 3.10.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'List', 'Chats', 'django.contrib.humanize', 'crispy_forms', 'crispy_bootstrap5'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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'] Template error: In template C:\Users\Fubara\Desktop\Desk\Web Dev\Django\TodoApp\Templates\detail.html, error at line 38 Reverse for 'completed_list_item' with arguments '('', '')' not found. 1 pattern(s) tried: ['completed\\-item/(?P<list_pk>[0-9]+)/(?P<item_pk>[0-9]+)/\\Z'] 28 : <h4 class="card-title">{{todo_list.title}}</h4> 29 : <p class="card-text">{{todo_list.description|linebreaksbr}}</p> 30 : <ul class="center list-unstyled"> 31 : <!-- {% comment %}{% endcomment %} --> 32 : {% for item in list_items %} 33 : … -
Cookiecutter : Stop the execution of the cookiecutter if user gives no as input to one parameter
Cookiecutter.json has a parameter which accepts "yes" or "no": { "test" : [ "yes", "no"] } if user selects "yes" then it should continue accepting the inputs further, if not it should stop. The same logic is included in pre_gen_project.py under hooks folder. try: if "{{ cookiecutter.test }}" == "yes": cookiecutter.prompt.read_user_variable("full_name","your_synthetic_test_name") else: sys.exit(0) except Exception as ex: print("Exception in pre_gen_project script") Problem here is , it is entering the else condition , but the cookie cutter execution is not stopping here. Any suggestion , Let me know. Thank you. -
Migrating 'openapi.Schema()' from drf-yasg to drf-spectacular
I'm migrating from drf-yasg to drf-spectacular, using the From drf-yasg to OpenAPI 3, and I've done most of my docs, but I have some problems triying to replace my old openapi.Schema(). By the docs Schema is not required and can be eliminated. Use a plain dict instead, but I'm not sure how to fit this dict when you have nested objects, for example, my code originaly was: @swagger_auto_schema( operation_summary="Text", operation_description="More text", request_body=openapi.Schema( "body", "Body params", openapi.TYPE_OBJECT, properties={ "params": openapi.Schema( type=openapi.TYPE_ARRAY, items=openapi.Items( type=openapi.TYPE_OBJECT, properties={ "param1": openapi.Schema(type=openapi.TYPE_INTEGER), "param2": openapi.Schema(type=openapi.TYPE_STRING), }, ), ) }, ), responses={ 200: openapi.Response( "Response", openapi.Schema( "response", type=openapi.TYPE_OBJECT, properties={ "status": openapi.Schema(type=openapi.TYPE_STRING, default="ok"), "details": openapi.Schema(type=openapi.TYPE_STRING), }, ), ), }, tags=["example"], I'm not sure how to deal with the type=openapi.TYPE_OBJECT and include the array type (I know about the many=True but again, not how to fit it in the dict). By the docs, it should go something like this? But where I should use the many=True here for the array? request={ "params": { "param1": OpenApiTypes.INT, "param2": OpenApiTypes.STR, } }, -
Run development server using django exe
I have been trying to run the exe file(created using pyInstaller) of my django project on the development server so that I can verify whether the it is working properly or not. Tried some commands and also asked Chatgpt but could find any suitable solution. The commands that I have tried: Input: manage.exe runserver Response: File "manage.py", line 11, in <module> File "manage.py", line 10, in main File "django\core\management\__init__.py", line 446, in execute_from_command_line File "django\core\management\__init__.py", line 440, in execute File "django\core\management\base.py", line 402, in run_from_argv File "django\core\management\commands\runserver.py", line 74, in execute File "django\core\management\base.py", line 448, in execute File "django\core\management\commands\runserver.py", line 111, in handle File "django\core\management\commands\runserver.py", line 118, in run File "django\utils\autoreload.py", line 682, in run_with_reloader File "Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_django.py", line 23, in _restart_with_reloader File "django\utils\autoreload.py", line 272, in restart_with_reloader File "django\utils\autoreload.py", line 259, in get_child_arguments RuntimeError: Script runserver does not exist. [19796] Failed to execute script 'manage' due to unhandled exception! Input: manage.exe runserver 127.0.01:8000 (Derived after running "manage.exe help runserver") Response: Same as above -
How Become a Successful Software developer and actually land a job [closed]
I have been coding since I was in 9th grade started with python and now I just passed 12th, to be straight forwards my question is what are the things that I have to do to actually land a job in tech industry. I know a lot about python and it's modules and I'm also familier with front end web development using django and react -
How to pass into a variable what was created [closed]
View and receiver I want to pass what was added to the message variable. How to do it? Looked in the documentation, but without success. -
Django JSONField with arrays filtering by substring
I've got a events JSONField in my model and I want to filter by value on key. Example object creation: MyModel.objects.create( name="test", events=[ {"type": "created", "info": "xxx"}, {"type": "sent", "info": "abc"}, ] ) So in events I have a list of events with same keys but different value. I want to filter by name and info values for doing autocompletion feature - so I need to filter by string icontains in info. What I figured out is MyModel.objects.filter(Q(name__icontains='abc') | Q(events__info__0__icontains='abc')) but it takes only first event from a list - if info match in second element then it is not placed in results. Is it possible to do with django orm? I want something like MyModel.objects.filter(Q(name__icontains='abc') | Q(events__info__<all>__icontains='abc')) -
Django: How to automatically restart gunicorn after my code changed
I'm developing a Django website, in which top menu should reflect changes in the page structure. In some sections (such as "About") changes are rare, so the menu is kept as a separate HTML file, which is included into the base template base.html: {% include "includes/menu_about.html" %} Although this works, there is a problem: the server doesn´t "see" that my menu_about.html file has changed, and, apparently, shows the page from cash, so the user doesn´t see the updated menu until I manually restart Gunicorn server. How is it possible to solve this problem? Looks like I have to make Gunicorn to restart automatically each time after my "Page" model saved. Perhaps, there is certain command in Django, which can be run on model save and restart the Gunicorn? Or may be certain settings in the Gunicorn itself? -
Update a field for all instances when a Many-to-many relationship is involved
I have the following: class Customer(model): stores = models.ManyToManyField(Store, related_name = "customers") subscriptions = models.ManyToManyField(Subscription, through = "CustomerSubscription") class CustomerSubscription(model): subscription = models.ForeignKey(Subscription) customer = models.ForeignKey(Customer) class Subscription(model): is_valid = models.BooleanField() For a given store instance: store = Store.objects.get(pk=1) I want to get all the subscriptions for all the customers and set is_valid to False. This is my attempt which appears to work: customers = store.customers.all() for c in customers: c.subscriptions.update(is_valid=False) I then tried using prefect_related: customers = store.customers.prefect_related("subscriptions") for c in customers: c.subscriptions.update(is_valid=False) But I don't believe I am doing this correctly as it resulted in more sql queries than my first attempt. How should I be doing this? -
How can I generate a pdf from django and send it by mail
estoy tratando de generar un pdf a partir de un html que diseñe para luego covertirlo en pdf y enviarlo por correo electronico, pero inteno generarlo y solo se generan desde el lado del cliente y no lo puedo enviar asi por el correoenter image description here I tried with pisa of xml2pdf and it only renders on the client side as far as it seems to me everything else generates blank pdf -
What "Tomcat/bypass/command/base64/.. " mean?
I don't know what is the problem exactly? Hello.. I built an website with Django framework and deploy it to Debian server, i install Apache web server on it then run the website.. So in the project i do some thing like this : Get the ip address from people who are visiting the main page in the website and save them for one day, and in the next day delete the old IPes and save for today and so on.. but the website has no domain name yet.. it still under trail until this moment.. I display the IPes on admin interface... Then wow!! I get this !! enter image description here Where they come from ?? And what doesn't the string i mentioned in orange box ? I searched on google it seem like an attack or something i don't know! So i delete the log file on Apache server after copy it on my device.. And now the time on my server does not work ?? I can't get the time with : datetime.datetime.now() In view.py file -
postgresql - cannot modify default "postgres" user
How to change, alter, postgres default values for my project? I have a django project which I try to deploy to digital ocean on an ubunto instance. In psql I create a new user with new_password and grant it all privileges to the new_db. Yet, these created entries are not connected to my project database. i.e. The values of the databases remain the default ones: Name/User/Password=postgres I note here the commands I run the Docean, ubuntu server: Assunming a new_user created (i.e. none root) and all psql packages are installed. sudo -u postgres psql CREATE DATABASE new_db; #DATABASE created; CREATE USER new_user WITH PASSWORD 'new_psw'; ALTER ROLE new_user SET client_encoding TO 'utf8'; ALTER ROLE new_user SET default_transaction_isolation TO 'read committed'; ALTER ROLE new_user SET timezone TO 'UTC'; GRANT ALL PRIVILEGES ON DATABASE new_db TO new_user; Quitting postgres, I my database value on my shell: The values remain the default ones: DATABASES {‘default’: {‘ENGINE’: ‘django.db.backends.postgresql’, ‘NAME’: ‘postgres’, ‘USER’: ‘postgres’, ‘PASSWORD’: ‘postgres’, ‘HOST’: ‘localhost’, ‘PORT’: 5432, ‘ATOMIC_REQUESTS’: False, ‘AUTOCOMMIT’: True, ‘CONN_MAX_AGE’: 0, ‘CONN_HEALTH_CHECKS’: False, ‘OPTIONS’: {}, ‘TIME_ZONE’: None, ‘TEST’: {‘CHARSET’: None, ‘COLLATION’: None, ‘MIGRATE’: True, ‘MIRROR’: None, ‘NAME’: None}}} I also tried the following: I then declared the new_user as the database … -
Django OneToOne field where one side of the relation is mandatory
Suppose I have these models: class Space(models.Model): item = models.OneToOneField(Item, null=True, on_delete=models.CASCADE) class Item(models.model): ... A Space can contain an Item, but it can be empty too. On the other hand, every Item must have a Space. It cannot exist in a void. I could create a field .space in my Item model (with null=False), but then Space.container can never be empty (raising a RelatedObjectDoesNotExist exception when creating/querying them). Handling these exceptions is cumbersome. I'd rather have Space.container return None (as is the case with my current setup). Is there an easy way to make .space in the Item model mandatory, but not the other way around? -
How to set the redirect URL in Django within the dispatch method with URL parameters
I have a custom Mixin that checks for the total usage of a particular service and based on that allows users to submit the form or redirect to the success_url with an error message of total usage. This works fine for URLs without any dynamic parameters like pk or slug. but with parameters, Django cannot find a URL pattern to redirect to the success_url. urls.py (URL file of Instagram app) # some other urls path('<int:post_id>/image/stock/', InstagramImageStockView.as_view() , name='instagram_image_stock'), path('<int:post_id>/image/stock/generate/', InstagramGenerateStockImageView.as_view(), name='instagram_fetch_stock_image'), # more URLs views.py class InstagramGenerateStockImageView(CustomMixin, FormView): form_class = InstagramStockImageForm success_url = 'instagram:instagram_image_stock' # other code custom mixin class CustomMixin: # other methods def check_generation_status_and_redirect(self, request, *args, **kwargs): if self.able_to_generate: return super().dispatch(request, *args, **kwargs) else: # Set an error message based on conditions. return redirect(self.success_url, kwargs=kwargs) def dispatch(self, request, *args, **kwargs): self.check_daily_count() return self.check_generation_status_and_redirect(request, *args, **kwargs) When a user reaches the limit I am getting NoReverseMatch error while redirecting to the success_url. I also tried by defining the success_url with reverse_lazy but not working. Thanks. -
how can I determine which ORM is the most suitable for my specific Django project requirements?
What are the factors to consider when choosing an ORM for a Django project, and how can I determine which ORM is the most suitable for my specific project requirements? I'm currently working on a new project and I'm looking for advice on the best ORM to use that doesn't require migration. I prefer to work with ORMs that simplify database interactions and reduce the amount of boilerplate code that I have to write. However, I've run into issues with ORMs that require migration for database schema changes. I'm hoping that some of you may have experience with ORMs that don't require migration and can offer recommendations. I'm particularly interested in ORMs that have a robust set of features, good documentation and are easy to use. Any suggestions would be greatly appreciated. Thank you in advance! -
Django ModelForm has no model class specified error
*** forms.py file *** I've checked most sites and videos and the issue is not solving. from django import forms from django.forms import ModelForm from .models import * class TaskForm(forms.ModelForm): class Mete: model = Task fields = '__all__' here is the views.py file * from django.shortcuts import render, redirect from .models import * from .forms import * # Create your views here. def home(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks':tasks, 'form':form} return render(request, 'home.html', context) here is the html file * <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home page</title> </head> <body> <h1>Todo project by Rohit.</h1> <form method="POST" action="/"> {% csrf_token %} {{ form.title }} <input type="submit" name="Create Task"> </form> {% for task in tasks %} <div> <a href="{% url 'deletepage' %}">Delete task</a> <a href="{% url 'updatepage' %}">Update task</a> {{task.title}} </div> {% endfor %} </body> </html>