Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create url to image in databse with expiration time
I have create model like: class Photo(models.Model): """ Photo model with automatically generated Thumbnail by TierPhotoSetting of UserTier """ user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) photo = models.ImageField(upload_to='photos', blank=False, null=False) and now I would like to create a new database object which stores a link to photo from Photo. This url link should have expiration time like 500 sec. How to serve user url to image which are active just some time? Thanks in advance. -
How can I call countries and cities to my dropdownlist with this json format
How do you get data from json doesn't have any id's/titles. I can't get the data to my dropdown selection. This is what I have so far...(and am new at this) Json file that looks like this: { "Afghanistan": [ "Herat", "Kabul", "Kandahar", "Molah", "Rana", "Shar", "Sharif", "Wazir Akbar Khan" ], "Albania": [ "Elbasan", "Petran", "Pogradec", "Shkoder", "Tirana", "Ura Vajgurore" ], "Algeria": [ "Algiers", "Annaba", "Azazga", "Batna City", .... register_1.html {% csrf_token %} <div class="col-md-6"> <div class="form-group"> <label for="inputStatus">Country</label> <select id="place-country" class="form-control-sm custom-select"> <option selected disabled>Country</option> {% for country_name in countries %} <option value="{{country.name}}">Country</option> {% endfor %} </select> </div> </div> <div class="col-md-6"> <div class="form-group"> <label for="inputStatus">City</label> <select id="place-city" class="form-control-sm custom-select" name="topic"> <option selected disabled>City</option> </select> </div> </div> views.py from django.http import JsonResponse import json import urllib.parse def get_cities_ajax(request): country_data = 'profileusers/static/profileusers/json/countries.json' url = country_data.urllib.parse.urlencode() data = request.get(url).json() print(data) for name in data: print(name) if request.method == "POST": country_name = request.POST['country_name'] try: countries = countries.objects.filter(name = country_name).first() cities = Topic.objects.filter(countries = countries) except Exception: data['error_message'] = 'error' return JsonResponse(data) return JsonResponse(list(cities.values()), safe = False) Or if I should use the form.py since its for registration? from django.http import JsonResponse import json import urllib.parse class ProfileForm1(forms.ModelForm): country = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label='Country:') city = … -
How to get count of foreign key relationship for each instance in queryset?
I have the following Models: # app_a/models.py class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_on = models.DateTimeField(auto_now_add=True) # app_b/models.py class PollerComment(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='PollerComment') user = models.ForeignKey(Account, on_delete=models.CASCADE) And this view to render the template: def render_pollboard(request): # Query Pollers poller_queryset = Poller.objects.all() # Convert to list qs_list = list(poller_queryset) # Shuffle the list shuffle(qs_list) # Retrieve comment count per Poller comments_qs = PollerComment.objects.filter(poller_id=poller.poller_id) [..] In the view I try to get the comment count for each Poller in poller_queryset. How to do this? Side note: I tried to implement the comment count as a method to the Poller model, but due to my design this leads into a circular import error of module of app_b/models.py -
Django/Heroku Error loading psycopg2 module: No module named 'psycopg2'?
Hi All I Re Creat django Local code Because my pc formatted and my project removed & when i push it on heroku when i try to open it again they give me this error 2021-09-20T14:55:18.814726+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/options.py", line 207, in contribute_to_class 2021-09-20T14:55:18.814726+00:00 app[web.1]: self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) 2021-09-20T14:55:18.814732+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/connection.py", line 15, in getattr 2021-09-20T14:55:18.814733+00:00 app[web.1]: return getattr(self._connections[self._alias], item) 2021-09-20T14:55:18.814733+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/connection.py", line 62, in getitem 2021-09-20T14:55:18.814733+00:00 app[web.1]: conn = self.create_connection(alias) 2021-09-20T14:55:18.814734+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 204, in create_connection 2021-09-20T14:55:18.814734+00:00 app[web.1]: backend = load_backend(db['ENGINE']) 2021-09-20T14:55:18.814734+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 111, in load_backend 2021-09-20T14:55:18.814735+00:00 app[web.1]: return import_module('%s.base' % backend_name) 2021-09-20T14:55:18.814735+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/init.py", line 127, in import_module 2021-09-20T14:55:18.814735+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-09-20T14:55:18.814736+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 29, in 2021-09-20T14:55:18.814736+00:00 app[web.1]: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) 2021-09-20T14:55:18.814736+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' 2021-09-20T14:55:18.814876+00:00 app[web.1]: [2021-09-20 14:55:18 +0000] [7] [INFO] Worker exiting (pid: 7) 2021-09-20T14:55:18.879919+00:00 app[web.1]: [2021-09-20 14:55:18 +0000] [8] [ERROR] Exception in worker process 2021-09-20T14:55:18.879943+00:00 app[web.1]: Traceback (most recent call last): 2021-09-20T14:55:18.879943+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 25, in 2021-09-20T14:55:18.879944+00:00 app[web.1]: import psycopg2 as Database 2021-09-20T14:55:18.879944+00:00 app[web.1]: ModuleNotFoundError: No module named 'psycopg2' 2021-09-20T14:55:18.879945+00:00 app[web.1]:undefined 2021-09-20T14:55:18.879945+00:00 app[web.1]: During handling of … -
Django celery beat not able to locate app to schedule task
I'm trying to schedule a task in celery. celery.py inside the main project directory from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE','example_api.settings') app = Celery('example_api') app.config_from_object('django.conf:settings',namespace="CELERY") app.conf.beat_schedule = { 'add_trades_to_database_periodically': { 'task': 'transactions.tasks.add_trades_to_database', 'schedule': crontab(minute='*/1'), # 'args': (16,16), }, } app.autodiscover_tasks() The project has a single app called transactions. function inside transactions/tasks.py @task(name="add_trades_to_database") def add_trades_to_database(): start_date = '20000101' #YYYYDDMM end_date = '20150101' url = f'https://api.example.com/trade-retriever-api/v1/fx/trades?fromDate={start_date}&toDate={end_date}' content = get_json(url) print(content) save_data_to_model(content,BulkTrade) settings.py """ Django settings for nordea_api project. Generated by 'django-admin startproject' using Django 3.2.7. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import environ env = environ.Env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env.read_env(env.str('BASE_DIR', '.env')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'example' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', … -
How can I solve the AttributeError?
Traceback (most recent call last): File "C:\Users\taink\PycharmProjects\upload\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\taink\PycharmProjects\upload\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\taink\PycharmProjects\upload\upload\views.py", line 23, in uploadFile documents = models.document.objects.all() Exception Type: AttributeError at /upload/ Exception Value: module 'django.db.models' has no attribute 'document' I'm trying to combine the two django projects that worked well when running each other, but it keep getting errors. Even if the code is separated and executed again after an error, the same error continues. What's the problem? -
Django - implications of READ COMMITTED isolation level in forms for users
So according to Django's doc, by default it implements Postgres' read committed isolation level. I understand the implications wrt to dirty read/writes. However, how does this play out from a user perspective in django? For instance: User A and User B both open the same model form. User A modifies the form, submit it and the commits the transaction, which passes. User B modifies fields "foo" and "bar" for instance. If "bar" has been modified by User A, will the transaction succeed for User B? If "foo" wasn't modified by User A, will the transaction succeed for B? In case a transaction doesn't succeed for B, would be details show up in non_form_errors? Or is the right thing to do is to manage it myself in the view & return a message/redirect to the user according to my business logic? Thanks! -
How to get passed JSON Data on Ajax Error?
I am using Django and Ajax. Im my view I have: return JsonResponse({"data": "success data"}, status=200) and return JsonResponse({"data": "error data"}, status=400) my ajax function looks like: $("#start_calculation_button").click(function () { $.ajax({ url: "/", type: 'get', data: { ... }, success: function (response) { console.log(response.data); }, error: function (response) { console.log(response.data); } }) }) But only the success function works? While the error part just gives back undefined Any idea's why it is that way? How can I fix it? -
authenticate on my models not User model in django
I have a model called Man which contain a name and a password do django support authentication on something other than User built-in model -
Passing URL Parameter to Django Form as an Attribute
Hello I am trying to use a URL parameter(id) in Django Model Forms as an attribute variable and getting an error as below. I am not sure if it's possible to pass id variable with calling "BidListing(id)" class like that. And getting it "BidListing(forms.ModelForm, id)" with this way. Error ...\forms.py", line 24, in <module> class BidListing(forms.ModelForm,id): TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases PS C:\Users\ycemalunlu\Desktop\commerce> Models.py class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listing_bids") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_bids") bid = models.DecimalField(max_digits=22, decimal_places=2) class Meta: ordering = ('-bid',) def __str__(self): return f"£{self.bid} bid made for {self.listing.title} by {self.user.username}" Forms.py class Minval(): def getminv(id): listing = Listing.objects.get(id=id) minv = listing.listing_bids.first().bid return minv class BidListing(forms.ModelForm,id): class Meta: minval = Minval.getminv(id) model = Bid fields = ('bid',) labels = {'bid': '',} widgets = {'bid': forms.NumberInput(attrs={'min':minval}) } Views.py def listing(request, id): return render(request, "auctions/listing.html", { "bid_listing": BidListing(id), }) -
Django 3.2 - django.db.utils.ProgrammingError: column "id" referenced in foreign key constraint does not exist
I am currently developping a django project, and I needed to move to PostgreSql databases. I did it just like this in my settings.py file: DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.postgresql_psycopg2', 'NAME' : 'lifeplaner', 'USER' : 'postgres', 'PASSWORD': <my_password>, 'HOST' : 'localhost', 'PORT' : '5432', } } I deleted all my migration directories and ran python manage.py makemigrations and python manage.py migrate, but I am getting this error (which is didn't occur when I was using sqlite3): (life-planer-app-env) C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\LifePlaner>python manage.py migrate Operations to perform: Apply all migrations: Calendar, Manager, ToDoList, admin, auth, contenttypes, django_celery_beat, django_celery_results, sessions Running migrations: Applying ToDoList.0001_initial...Traceback (most recent call last): File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "id" referenced in foreign key constraint does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\user\Desktop\Programmation-Python\Projets\Applications\LifePlanerApp\life-planer-app-env\lib\site-packages\django\core\management\commands\migrate.py", … -
Django How to pass signals in Abstract User model for create any custom model?
I have an Abstract user model. Where I have three type of user and I also have three custom model for three user. I want to pass signals in my Abstract user model for create my custom model. I have an custom model which name is MyAuthors. If I already have any user in my Abstract user model and save him as author but don't have any objects in MyAuthors model then it will create an objects in MyAuthors model for this user. I tried this code but didn't create user objects in MyAuthors model. class UserManagement(AbstractUser): is_blog_author = models.BooleanField(default=False) is_subscriber = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class MyAuthors(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) is_blog_author = models.BooleanField(default=False) @receiver(post_save,sender=settings.AUTH_USER_MODEL) def user_objetcs(sender,instance,created,**kwargs): if created: author = MyAuthors.objects.filter(user=instance) #here I am checking does user have or not any profile in MyAuthors model. if not author: #if user don't have any objects in MyAuthors model then it will create MyAuthors.objects.create(user=instance,is_blog_author=instance.is_blog_authors) -
How to get two RichText features to be mutually exclusive
So basically I've added two custom features for coloring text to a RichTextBlock, and I'd like to make them so selecting one for a portion of text would automatically unselect the other color button, much like it's already the case for h tags. I've searched for a bit but didn't find much, so I guess I could use some help, be it advice, instruction or even code. My features go like this : @hooks.register('register_rich_text_features') def register_redtext_feature(features): feature_name = 'redtext' type_ = 'RED_TEXT' tag = 'span' control = { 'type': type_, 'label': 'Red', 'style': {'color': '#bd003f'}, } features.register_editor_plugin( 'draftail', feature_name, draftail_features.InlineStyleFeature(control) ) db_conversion = { 'from_database_format': {tag: InlineStyleElementHandler(type_)}, 'to_database_format': { 'style_map': { type_: {'element': tag, 'props': {'class': 'text-primary'}} } }, } features.register_converter_rule( 'contentstate', feature_name, db_conversion ) The other one is similar but color is different. -
Form is not bound in Django
I'm trying to integrate Django with htmx. I want to render a form inside a table. but when I enter some data and submit it says the form is not bound. This is the view: def hx_payment_item_create(request, payment_id): payment = get_object_or_404(Payment, pk=payment_id) form = forms.PaymentItemCreateFromPaymentForm(request.POST or None) if request.method == "POST": if form.is_valid(): item = form.save(commit=False) item.payment = payment item.save() if request.htmx: return redirect("core:hx-payment-item-detail", pk=item.pk) return redirect("core:payment-item-detail", pk=item.pk) else: print(form.errors) context = {"form": form, "payment": payment} return render(request, "core/partials/payment_item_form.html", context) This is the template that will be rendered inside the table: <tr hx-target="this" hx-swap="outerHTML"> <form method="POST"> {% csrf_token %} {{ form.non_field_errors }} {% for hidden_field in form.hidden_fields %} {{ hidden_field.errors }} {{ hidden_field }} {% endfor %} {% for field in form.visible_fields %} <td> <label for="{{ form.subject.id_for_label }}">{{ field.label }}</label> {{ field.errors }} {{ field }} {{ field.help_text }} </td> {% endfor %} <td> <button type="submit" hx-post="#some_url"> submit </button> </td> <td> <button hx-get="#another_url" type="button"> cancel </button> </td> </form> </tr> -
Migrate a Dash app with multiple outputs to Django app
I have a dash app that in my app.py I have functions with many outputs. Is feasible somehow to migrate to Django? -
Why won't elastic beanstalk render css for the django admin site?
I am following this guide on deploying a django app to AWS Elastic Beanstalk : https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html After running eb open, the css for the admin site does not render. It works when running the development server at 127.0.0.1:8000/admin but not when deployed to EB. I have followed this guidance but it is still not working Elastic Beanstalk does not load the Django admin static files Can someone explain why this is happening? -
Favicon and manifest.json is not loading in Django / React Project Setup
I already have seen possible scenarios to solve this problem with the help of this already posted question and answer. how-to-add-favicon-to-django-app-with-react-front-end? But I'm unable to reproduce the solution. Now the Problem is Favicon is generated automatically with a command: npm run build In the build dir which the Django is serving. This is how the build dir is generated after npm run build command and the build is generated from this public folder index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm … -
Djangorestframework returns: TypeError: get_extra_actions() missing 1 required positional argument: 'self' when declaring get()
I am a little confused in my code I have: from django.db.models import query from django.shortcuts import render from rest_framework.views import APIView from .models import Publication from rest_framework.response import Response from .serializer import PublicationSerializer # Create your views here. class PublicationView(APIView): serial_class = PublicationSerializer() def get_extra_actions(self): return [ self.get() ] def get(self, request): detail = [ {'pub_id': i.pub_id, 'pub_date': i.pub_date, 'title': i.title, 'description': i.description, 'link': i.link} for i in Publication.objects.all() ] return Response(detail) but I am still getting a return the above error. Any thoughts or help? Let me know! -
Django many to many fields
i try to created online movies site, i write models.py this is serial models class Serial(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) images = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=30) status = models.CharField(choices=STATUS_CHOICES, max_length=100) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) def get_absolute_url(self): return reverse('post', kwargs={"post_slug_serial": self.slug}) def __str__(self): return self.title this is for add episode and series : example Season 1 --> series 1 and etc season_num = ( (" 1 ", "Season 1"), (" 2 ", "Season 2"), (" 3 ", "Season 3"), (" 4 ", "Season 4"), (" 5 ", "Season 5"), (" 6 ", "Season 6"), (" 7 ", "Season 7"), ("8 ", "Season 8"), (" 9 ", "Season 9"), ) class episodebi(models.Model): """ Information about specific TV Show episodes """ tv_show = models.ForeignKey(Serial, on_delete=models.CASCADE) season = models.CharField(choices=season_num,max_length=50) series = models.IntegerField(max_length=50) title = models.CharField (max_length=50) class Meta: unique_together = ('tv_show', 'season','series') def __str__(self): return self.title and this is my view.py def serieDetails(request,post_slug_serial): get_serie = Serial.objects.filter(slug = post_slug_serial) epis = episodebi.objects.all() return render(request, '2/seriel_desc.html', {"serie":get_serie,"epis":epis}) when i try to add html this cycle HTML {% load static %} {% for i in epis %} <h1>{{ i.tv_show … -
CS50W: Project2 (Commerce) / Django
I am finishing a Django app on auctions. I am required to make a view for each listing showing the current bids on this listing, the details, and a form to be able to place a bid on the listing. I am having one minor issue in updating the listing price when a higher bid is placed by a user. The problem is in the logic of the listing_view function, but I can't spot it: def listing_view(request, listing): this_listing = Listing.objects.get(listing_name=listing) bid_count = this_listing.bids.count() if request.method == "POST": form = BidForm(request.POST) current_user = request.user if form.is_valid(): newest_bid = form.cleaned_data["bid_price"] if newest_bid >= this_listing.current_price: new_bid = Bid(listing=this_listing, bid_price=newest_bid, owner=current_user) new_bid.save() bid_count += 1 this_listing.current_price = newest_bid this_listing.bids.add(new_bid) return HttpResponseRedirect(reverse("auctions:listing_view", kwargs= {'listing':this_listing.listing_name})) else: return HttpResponse("Error") else: return render(request, "auctions/listing.html", { "listing": this_listing, "form": BidForm, "count": bid_count }) If you want the model definition of Listing and Bid, I can provide them, but I believe the issue is in the listing_view logic. -
Django REST Framework: how to make the index route browsable if routes are prefixed?
I've no use for the index route api.domain.tld/. Instead my routes start quite nested: api.domain.tld/v1/some/thing/ api.domain.tld/v1/foo/bar/ When I visit api.domain.tld/ I get a 404 - which makes sense, but I'd like to get browsable suggestions of the nested routes instead. Relevant code: router = routers.DefaultRouter() router.register(r'some', ThingViewSet) router.register(r'foo', BarViewSet) urlpatterns = # path('', '...') - is not in use path('v1/', include(router.urls)) ] Any idea? Thanks in advance! -
Method Not Allowed in Django (Django-get Method)
I want to find the title as I give in the search field as I call the search/get method I get I trying to search the title with his name the error ; Error : Method Not Allowed: /api/tutorials [20/Sep/2021 18:18:35] "GET /api/tutorials?title=creating HTTP/1.1" 405 40 view.py: ' @api_view(['GET']) def tutorial_list(request): if request.method == 'GET': paginator = PageNumberPagination() paginator.page_size = 4 tutorials = Tutorial.objects.all().order_by('-id') title = request.GET.get('title', None) if title is not None: tutorials = tutorials.filter(title__icontains=title) result_page = paginator.paginate_queryset(tutorials, request) tutorials_serializer = TutorialSerializer(result_page, many=True) return paginator.get_paginated_response(tutorials_serializer.data) ' urls.py: ' urlpatterns = [ url(r'^api/tutorials/$', views.tutorial_list), url(r'^api/tutorials$', views.tutorial_post), url(r'^api/tutorials/(?P[0-9]+)$', views.tutorial_detail), url(r'^api/tutorials/published$', views.tutorial_list_published) ] ' -
SimpleJWT cannot authorize after changing the SECRET_KEY in django
I have a really weird problem with rest_framework_simplejwt package. It was working until I decided to change the SECRET_KEY of my django project. After that I can get the access and refresh token, but they don't work as expected. { "type": "authentication_error", "code": "token_not_valid", "detail": "Given token not valid for any token type", "attr": "detail" } All I did was changing only one character in my secret key. I'm using: Django 3.1.13 rest_framework_simplejwt 4.7.1 It would be awesome if I can get some help. Thanks. -
How to solve graphdoc markdown error in Django
I am trying to output the graphql docs in Django using graphdoc package and the following source code: return HttpResponse( graphdoc.to_doc(FileUploadGraphQLView().schema), content_type='text/html' ) however, I get the following error: -
How can I use uWSGI Spooler in Django?
I'm trying to run concurrent tasks using uWSGI Spooler instead of Celery in Django. I have found a few resources like this, this, and this, but nothing works. I have encountered many errors in this journey, and I have fixed them using solutions I found online, and right now this is what I have: Setup uwsgi.ini [uwsgi] pythonpath = /path/to/djproj wsgi-file = /path/to/djproj/wsgi.py uid = myuid module = wsgi:application master = true processes = 1 threads = 10 lazy-apps = true http = 0.0.0.0:8080 vacuum = true log-format = %(ltime) Worker: %(wid) %(status) %(method) %(uri) Size: %(size) log-date = %%Y %%m %%d %%H:%%M:%%S.000 # Let django handle most of the logging disable-logging = true log-5xx = true harakiri = 60 harakiri-verbose = true stats = /tmp/djproj_stats.socket # Spooling spooler = /path/to/tasks spooler-harakiri = 600 import = djproj.tasks tasks.py import logging logger = logging.getLogger(__name__) try: from uwsgidecorators import spool logger.warning("Imported spool successfully.") except Exception: logger.warning("Couldn't import spool.") def spool(func): def func_wrapper(**arguments): return func(arguments) return func_wrapper @spool def run_task(arguments): logger.warning("Running in spool.") from djproj.myapp.models import MyModel obj = MyModel.objects.get(id=arguments["obj_id"]) obj.run() djproj/myapp/models.py # ... def prepare_spooler_args(**kwargs): args = {} for name, value in kwargs.items(): args[name.encode("utf-8")] = str(value).encode("utf-8") return args class MyModel(models.Model): # ... …