Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django vs Flask
Django vs Flask I've created an AI language model in the form of an API. Now I want to integrate this model into your website. Which do you think is better, Django or Flask? Now, I'm not sure what the difference is between Django and Flask, and I'd like to ask you which one you would recommend if I were building a website. -
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>`
I want to async view with my django rest framework api_view but I am getting the above error even if I had awaited my response. Here is my view @api_view(['POST']) @permission_classes([AllowAny]) @authentication_classes([]) async def login(request): email = request.data.get('email') if email is None or email == '': return Response(data={'success': False, 'message': 'Invalid credentials'}) user = await sync_to_async(User.get_by_email)(email=email) if user is not None and user.is_active and user.check_password(raw_password=request.data.get('password')): serializer = UserSerializer(user) # TODO async tokens_map = await sync_to_async(AuthUtils.generate_token)(request=request, user=user) asyncio.run(create_preference(request, user=user)) return Response({'success': True, 'user': serializer.data, 'tokens': tokens_map}) return Response(data={'success': False, 'message': 'Invalid login credentials'}, status=status.HTTP_404_NOT_FOUND) Is there any way to use async views with django in an efficient way? What about asyncio, like if I wrap all of my blocking methods with asyncio.run, what will be the impact with the performance? Can asgi based servers will take the full advantage of asyncio? -
How to approve PayPal subscription automatically without approval URL
I am facing an issue with integrating PayPal subscriptions into my project. Currently, the integration process involves: adding PayPal as a payment method on my website using PayPal checkout. Then, on the 'Plans & Pricing' page, I select a subscription plan, which creates a new PayPal subscription using the PayPal REST API in Backend. From there, the API generates an approval URL, which redirects me to the PayPal Approval Page where I must input my PayPal credentials to approve the subscription. However, what I desire in my project is: the ability to subscribe to a plan without being redirected to the Approval Page and having to input my PayPal credentials again. *Freelancer.com, for example, has this functionality where after verifying the payment method, there is no need to input PayPal credentials again when subscribing to a plan. * I would greatly appreciate any help in achieving this functionality. Thank you, Chris -
How Do I Retrieve Data From a Form after A Button is Clicked using Django
I have searched for the solution for hours, and all of the solutions that I have found do not work (I'm probably doing something wrong). I want to be able to retrieve data entered by the user in the "email" and "password" fields of my login page. However, I can't find a working solution. Help?! # the login form <form> <label>First Name</label> <input id="first-name-input" type="text" placeholder=""/> <label>Last Name</label> <input id="last-name-input" type="text" placeholder=""/> <label>Email</label> <input id="email-input" type="email" placeholder=""/> <label>Password</label> <input id="password-input" type="password" placeholder=""/> <label>Confirm Password</label> <input type="password" placeholder=""/> <input type="button" value="Submit"/> <closeform></closeform></form> -
Django Project: Trying to understand why my Django project is showing the error Understanding TypeError Invalid path type list:
I am trying to understand why my Django project is saying that it cannot understand my paths. According the instructions of the book django for beginners I need to run the python manage.py runserver command to load the website but it stops me. It shows the following when I get the error: Error Message (.venv) andrewstribling@Andrews-MBP pages % python manage.py runserver Watching for file changes with StatReloader Performing system checks... Traceback (most recent call last): File "/Users/andrewstribling/Desktop/code/pages/manage.py", line 22, in <module> main() File "/Users/andrewstribling/Desktop/code/pages/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/commands/runserver.py", line 111, in handle self.run(**options) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/commands/runserver.py", line 118, in run autoreload.run_with_reloader(self.inner_run, **options) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 671, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 660, in start_django reloader.run(django_main_thread) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/utils/autoreload.py", line 343, in run autoreload_started.send(sender=self) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/dispatch/dispatcher.py", line 176, in send return [ File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/dispatch/dispatcher.py", line 177, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/autoreload.py", line 43, in watch_for_template_changes for directory in get_template_directories(): File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/autoreload.py", line 20, … -
'pwa' in django brings a error and its not found yet its installed as one of the requirements in the pip list.. It keeps on bringing an error
File "/Users/mac/Desktop/rental-house-management-system-main/myenv/lib/python3.11/site-packages/Django/apps/config.py", line 228, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/import lib/init.py", line 126, in import_module ModuleNotFoundErrorthe error: No module named 'pwa' was expecting the server to run and execute my project -
Postgres Django data disappearing from containerized services
Below is the docker compose file which I used to launch two services, postgres database and django application. Somehow, my data in postgres is disappearing. I am not sure whether it is a Django problem or Postgres problem. It doesn't get disappear quickly, after couple of days suddenly I am seeing nothing in the database. Even the django superuser getting disappear. But the docker services are still running. docker compose ls shows the services. version: "3.9" services: db: image: postgres:11 volumes: - pgdata:/var/lib/postgresql/data environment: - PRODUCTION=false - POSTGRES_HOST_AUTH_METHOD=trust - PGDATA=/var/lib/postgresql/data env_file: - ./config/.env.dev ports: - "5435:5432" web: build: . command: > sh -c "/wait-for-it.sh db:5432 -- python manage.py migrate && python manage.py runserver 0.0.0.0:80" volumes: - .:/code - ./wait-for-it.sh:/wait-for-it.sh environment: - PRODUCTION=false env_file: - ./config/.env.dev ports: - "80:80" depends_on: - db volumes: pgdata: -
Cannot add author field in django
but when i'm making python manage.py makemigrations, it says that nothing has changed and in admin panel i only have title and body fields, but not author, can you please tell me where i did some mistakes? i have that django code in blog/models.py: from django.db import models from django.urls import reverse from django.contrib.auth.models import User # Blog Models class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE), body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse("post_details", kwargs={"pk": self.pk}) -
How to model biderection relation with a django model?
I have three simple models : Country, state, cities A country has several states A states has severals cities, and only one country A cities has one state I'd like to model this using django class Country(models.Model): name = models.CharField() ... States ??? class State(models.Model): name = models.CharField() country = models.ForeignKey(City, on_delete=models.CASCADE) ... Cities ??? class City(models.Model): name = models.CharField() State = models.ForeignKey(State, on_delete=models.CASCADE) I'm am not very clear about how to represent the links between state and country, as well as the link between state and cities, since there is no "OneToMany" class. Additionnaly, I'd like it to be biderectionnal (I'd like to be able to access the state from the cities, as well as the cities from the states and so on..) How to to that ? -
django-comments-xtd clashing with wagtail-localize
I am following the official tutorial for wagtail-localize, and I am at the step to set up a second locale. When I hit save, I get: DoesNotExist at /admin/locales/new/ XtdComment matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/admin/locales/new/ Django Version: 4.2.2 Exception Type: DoesNotExist Exception Value: XtdComment matching query does not exist. How can I prevent django-comments-xtd to get involved here at all? I am using the latest versions of both packages: Django>=4.2,<4.3 wagtail>=5.0.2,<5.1 django-comments-xtd==2.9.10 wagtail-localize==1.5.1 Thank you! EDIT: I CAN actually create a new locale if I do not synchronize it from my default one. When I then try to edit the new locale to enable synchronization, I get the same error again. -
Djangocms-blog Reverse for 'post-detail' not found in another languages
I wrote a cms plugin that show a blog details and link. it work's on the EN language but in FA post.get_absolute_url() has a error, that says: Reverse for 'post-detail' not found. 'post-detail' is not a valid view function or pattern name. I'm using djangocms-blog==1.2.3, django==3.2.20 and djangocms==3.11.3 My models.py: class ArticleView(CMSPlugin): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="article_view")` My cms_plugins.py: @plugin_pool.register_plugin class ArticleViewPlugin(CMSPluginBase): model = ArticleView name = _("Article View Plugin") render_template = "article_view.html" cache = False In my article_view.html: <a class="fusion-link-wrapper" href="{{ instance.post.get_absolute_url }}"aria-label="{{ instance.post.title }}"></a> My urls.py: from cms.sitemaps import CMSSitemap from django.conf import settings from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from django.urls import include, path admin.autodiscover() urlpatterns = [path('sitemap.xml', sitemap, {'sitemaps': {'cmspages': CMSSitemap}}), path('', include('djangocms_blog.taggit_urls')),] urlpatterns += i18n_patterns(path('admin/', admin.site.urls), path('', include('cms.urls')), path('taggit_autosuggest/', include('taggit_autosuggest.urls'))) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) urlpatterns += static(settings.STATIC_URL, document_root=settings. STATIC_ROOT) error image: I tried to change languages in settings and rebuild the FA page but nothing happened -
Module not found in django
I have a django project with the following structure: game_app lobby_app __init__.py lobby_serializers.py user_app __init__.py user_serializers.py manage.py When I try to import user_serializers/UserSerializer into lobby_serializers.py with from game_app.user_app.user_serializers import UserSerializer I receive module not found from Python. Why is that? I've tried all kinds of import statements, relative, absolute, etc. and I always receive module not found or relative import beyond top level package error. -
How to properly manage CSRF with a React frontend and a Django backend
Ive found that, using Django, CSRF tokens are required under scenarios (and should in general be): For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’ field must be present and correct. If it isn’t, the user will get a 403 error. I have found a great deal of documentation and examples relevant only when Django is rendering the page templates. In this case, your templates can use special {% csrf_token %} token to add a hidden field that, when submitted, allows the backend to effectively validate the form's origin. So how does this generally work when Django is not rendering the pages? I can contrive a simple example where the frontend just uses React and the backend is strictly an API. I've found other documentation that claim you can decorate your backend API methods with such things as @csrf_protect or @ensure_csrf_cookie. However, the decorators instruct Django to set CSRF tokens on backed replies for some view/API request. Imagine a simple "login" type of scenario: React frontend renders Login page with form React frontend submits form with PUT to backend for auth According to any docs or … -
Django project: Failed to load resource: the server responded with a status of 404 (Not Found) error for media files
My website was working fine in both development and production, until I tried to add a google analytics tag to the website which I did incorrectly at first (accidentally put it outside of the head element). After doing this, my site started throwing the above 404 error for every media file it tried to load in production, even though the media files are all in the location that the site seems to be trying to access. The site also works perfectly fine in development with the exact same setup. Here is the full error I am receiving for every media file on my site: media_file.ext Failed to load resource: the server responded with a status of 404 (Not Found) Below are the relevant parts of my settings.py: BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and in my urls.py of my project I have included: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I tried both putting the google analytics tag in the head element, which did not work, and then taking the google analytics tag out, which also did not work. I have also tried re-adding the media files to my database by changing the images associated with each django object, … -
error: expected an identifier. expected a valid attribute name
{% for product in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='/media/{{ product.get("image") }}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ product.get("product_name") }}</h5> <p class="card-text">{{ product.get("desc") }}</p> <button id="pr{{product.get("id")}}" class="btn btn-primary cart">Add To Cart</button> </div> </div> </div> I was building a Django e-com platform and now I am getting this error for the image src tag ERROR: Expected an identifier. |Expected a valid attribute name, but instead found " ' ", Which is not part of a valid attribute name. How to fix this error? -
How to get hotels near a location using Google places api in a django framework?
I am working on a project using django framework. I want to use google places api to get hotels near a location(location as an input from the user). How to do that? I am new to django framework and integrating different APIs and there is not much information about this anywhere. -
How to use django.shortcuts.redirect outside the view function?
I am making a STT app on my website which uses openai-whisper. repo in need https://github.com/AkioKiyota/arge-test General Purpose Giving users a display/feedback about the process, and running a process without intervening the page. Working steps are like this: You upload your mp4-mp3 file throught form, You click the STT button next to your audio-clip-name, It downloads the whisper model(small), which happens once, Whisper transcribes the mp3 throught its path, Returns the result. Just ignore the div says 'last speech to text' its normaly where it should be showing it. Current script views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import AudioStoreForm from .models import AudioStore import whisper def index(request): audios = AudioStore.objects.all() if request.method == 'POST': form = AudioStoreForm(request.POST, request.FILES) print(form.is_valid()) if form.is_valid(): form.save() return HttpResponseRedirect('') else: form = AudioStoreForm() return render(request, 'index.html', {'form': form, 'audios': audios}) def stt(request, audio_name): module = whisper.load_model('small') audio = AudioStore.objects.get(name=audio_name) result = module.transcribe(audio.audio_file.path, verbose=False) return HttpResponse(result['text']) The Issue The problem is, page just keep loading while the transribe on the process. But i atleast want to add a reloading icon to show user that its actualy working and he should wait. I have tried using Threads like this: views.py def … -
How to get installed package from broken virtual environment python
I had venv that installed Django and python version3.8. After upgrading my ubuntu my virtual environment doesn't work anymore and it doesn't recognize the pip command and it returns: ModuleNotFoundError: No module named 'pip' After searching I found out the virtual environment is broken after upgrading and the best way is to remove venv directory and create again and install your packages again but I don't have my installed package list (using pip freeze > list.txt) so now how can I get installed package list from the broken virtual environment? I can see the list of directories here: $ ls venv/lib/python3.8/site-packages/ but I don't have it -
Timezone in JavaScript(Frontend) and Python(Backend) in Django
I could get the timezone Asia/Tokyo with Intl.DateTimeFormat().resolvedOptions().timeZone in JavaScript in index.html Django Template (Frontend) as shown below: {% "templates/index.html" %} <script> console.log(Intl.DateTimeFormat().resolvedOptions().timeZone) // Asia/Tokyo </script> And, I could get the timezone Asia/Tokyo with tzlocal.get_localzone_name() in Python in test Django View (Backend) as shown below: # "views.py" from django.http import HttpResponse import tzlocal def test(request): print(tzlocal.get_localzone_name()) # Asia/Tokyo return HttpResponse("Test") Now, I set San Francisco to Location in my browser Google Chrome: Then, I could get the timezone America/Los_Angeles with Intl.DateTimeFormat().resolvedOptions().timeZone in JavaScript in index.html Django Template (Frontend) as shown below: {% "templates/index.html" %} <script> console.log(Intl.DateTimeFormat().resolvedOptions().timeZone) // America/Los_Angeles </script> But, I could still get the timezone Asia/Tokyo with tzlocal.get_localzone_name() in Python in test Django View (Backend) as shown below: # "views.py" from django.http import HttpResponse import tzlocal def test(request): print(tzlocal.get_localzone_name()) # Asia/Tokyo return HttpResponse("Test") My questions: Why does tzlocal.get_localzone_name() in Python in test Django View (Backend) still get the timezone Asia/Tokyo? Which timezone does Intl.DateTimeFormat().resolvedOptions().timeZone in JavaScript in index.html Django Template (Frontend) get, my browser timezone or my computer timezone? Which timezone does tzlocal.get_localzone_name() in Python in test Django View (Backend) get, my browser timezone or my computer timezone? -
why does it show "No installed app with label 'learning_logs' " when i try to migrate while I have it in the list of installed apps in settings.py?
i have made an app for a project in django and wrote a class in models.py . i have also included the name of app in the list of INSTALLED_APPS in settings.py . after it, when i try to migrate this change, it says "No installed app with label 'learning_logs'" the relevent screenshots: please help. i tried to do the same thing many times and it didn't work. i expected to get a success message but it showed other( as seen in screenshot) -
How to pass a variable from template to a view
My page has two models into it. They all inherit from one base model: Entry. class Entry(models.Model): author_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) author_id = models.PositiveIntegerField() author = GenericForeignKey("author_type", "author_id") text = models.TextField() class Meta: abstract=True ordering = ["date_created", "date_updated"] class Post(Entry): comments = GenericRelation(Comment, related_query_name="post") def __str__(self): return f"POST(ID{self.id})" class Discussion(Entry): head = models.CharField(max_length=60) comments = GenericRelation(Comment, related_query_name="discussion") def __str__(self): return f"DISCUSSION(ID{self.id})" Template: {% block main %} {% for entry in entries %} <div class="card" style="width: 18rem;"> <img src="{{entry.image}}" class="card-img-top" alt="..."> <div class="card-body"> {% if entry.head %} <h5 class="card-title">{{ entry.head }}</h5> {% else %} <p class="card-text">{{entry.text|slice:"0:20"}}</p> {% endif %} <a href="{% url 'posts:comments' entry.id %}" class="btn btn-primary">Comments</a> </div> </div> {% endfor %} {% endblock %} How can I pass a variable that will distinguish them in a corresponding view, or are there any better ways of doing it? <a href="{% url 'posts:comments' entry.id %}" class="btn btn-primary">Comments</a> My guess is that I need to pass a variable in a URL tag, that will be passed in a view, but I don't know how to do it. Is it the way? Or can I implement it in some better way? -
How do I resolve the Django error "object of type 'int' has no len()" when creating an object in the admin site?
I'm aware of what the error means, the length function is being called on an integer, whereas it only takes a string. However, the tracelog is not particularly helpful and I'm struggling to identify where this error is happening. C:\Users\callu\PycharmProjects\DjangoTests\venv\Lib\site-packages\django\forms\boundfield.py, line 162, in _has_changed return field.has_changed(initial_value, self.data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … Local vars C:\Users\callu\PycharmProjects\DjangoTests\venv\Lib\site-packages\django\forms\models.py, line 1650, in has_changed if len(initial) != len(data): ^^^^^^^^^^^^ It happens when I try and create a new Post object in the admin site so I'm assuming there's an error somewhere in my Post Model, have I created one of the wrongs as the wrong type? class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, default=None, null=True) title = models.CharField(max_length=100) slug = models.SlugField(blank=True) description = models.TextField(max_length=500) date = models.DateTimeField(auto_now_add=True) url_link = models.URLField(default=None, blank=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_support", default=0, blank=True) tags = models.ManyToManyField(Tag, blank=True) class Meta: ordering = ('-date',) def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:post_detail", args=(str(self.id),)) Weirdly I can create a Post object fine from my front end, it's just when I try to use the admin site that it throws the error. -
Django register error not fully translated
Standard error massage during registration is: "user account with this email already exists." After I changed LANGUAGE_CODE to 'pl' in settings.py I get: "Istnieje już user account z tą wartością pola email." Instead of "user account" should be "konto użytkownika". Translation mistake is so obvious that I thought that "user account" is somewhere in my project files so I searched my django project and there is no single string in any of my files. How to fix this translation? In django I use 'rest_framework' and 'rest_framework_simplejwt' -
Django Rest framework
I have getting a error 400 bad request when registration. How can I fix it? Suggest something to fix it. I have done authentication in views, sent mail class to sending mail for otp verification to user I'm expecting a suggestion to fix it -
When I click to reserve, I can't save the reservation
I have received the value from the search page and shown in the booking page but also want to record that value as room, details, booking date, booking end and total price of the booking. but cannot save the value view.py def booking_cat_hotel(request, room_number, check_in_date, check_out_date): one_room = Room.objects.get(room_number=room_number) num_days = (datetime.strptime(check_out_date, '%Y-%m-%d').date() - datetime.strptime(check_in_date, '%Y-%m-%d').date()).days total_price = num_days * one_room.price if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.room = one_room booking.start_date = datetime.strptime(check_in_date, '%Y-%m-%d').date() booking.end_date = datetime.strptime(check_out_date, '%Y-%m-%d').date() booking.total_price = total_price booking.save() return redirect('completed', booking_id=booking.id) else: form = BookingForm(initial={ 'room': one_room, 'room_number': one_room.room_number, 'start_date': check_in_date, 'end_date': check_out_date, }) context = { "one_room": one_room, "check_in_date": check_in_date, "check_out_date": check_out_date, "form": form, "total_price": total_price, } return render(request, 'cat_hotel/cat_hotel.html', context=context) html <form action="{% url 'booking_cat_hotel' room_number=one_room.room_number check_in_date=check_in_date check_out_date=check_out_date %}" method="POST"> {% csrf_token %} <div class="container"> <div class="card p-4 mt-5"> <div class="row g-3"> <div class="col-12 mb-4"> <div class="col-12 mb-4"> <h4>Room {{ one_room.room_number }}</h4> <span class="text-muted">{{ one_room.description }}</span> <input type="hidden" name="room_number" value="{{ one_room.room_number }}"> <input type="hidden" name="room_description" value="{{ one_room.description }}"> </div> </div> <div class="col-lg-2 col-md-6 ml-3"> <h5>Check-in Date</h5> <p class="text-primary">{{ check_in_date }}</p> <input type="hidden" name="check_in_date" value="{{ check_in_date }}"> </div> <div class="col-lg-6 col-md-12"> <h5>Check-out Date</h5> <p class="text-primary">{{ check_out_date }}</p> <input type="hidden" …