Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django STATIC_URL with full domain breaks static assets locally
When working locally on a Django project that uses static files and the default static files backend, I am running into an issue when I want to get full absolute urls to the static files instead of only the path. My settings: DEBUG = True BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = ["django.contrib.staticfiles", ...] STATIC_ROOT = BASE_DIR / "static_root" STATIC_URL = "/static/" MEDIA_ROOT = BASE_DIR / "media_root" MEDIA_URL = "/media/" STATICFILES_DIRS = (BASE_DIR / "static",) STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ) Everything works, the admin's CSS is loaded, images work, etc. But when I get the path of a file with this code: from django.contrib.staticfiles.storage import staticfiles_storage static_path = staticfiles_storage.url("path_to_folder/some_file.jpg") That result is a relative path: /static/path_to_folder/some_file.jpg. This is a problem when these urls are used from my external frontend: it now has to prepend the backend's base url to all static assets. But if I'd want to deploy the static assets to S3 for example, in production, then I should not prepend these paths with the domain of the backend. So what I tried to do was to change the STATIC_URL setting to http://localhost:8000/static/. That way the full url is passed to the frontend, but I could really easily change this … -
Django autogenerate/share URLS
This is more of a general question on what tools and how I should set something up... Background: I am a relative beginner and I made a website called wordlegolf which is very similar and popular to the original wordle game but it tracks your score and has a scoreboard page that shows everyone on the site's scores. What I need help with: I want to make it so you can create your own scoreboard or league so that not every person on the site goes to one scoreboard. So you can have a scoreboard with your friends or family. I want to make it so you can create a league and then share a unique URL to invite people to that league. I was looking into channels to do this but I think that is more than what I need. I'm going to have to adjust my database but I mostly just wanted a project or explanation on how to create unique autogenerated URLs and how to create objects in a database to match that URL. I haven't tried much, just been looking around on what to use and how to achieve my goal and getting more confused. also … -
Custom is_valid() Serializer Django
I need to write custom check if data in body of a request is_valid() Below is my serializer class class UserSerializer(serializers.ModelSerializer): uid = serializers.IntegerField() user_id = serializers.IntegerField() u_name = serializers.CharField(max_length=50) age = serializers.CharField(max_length=100) email = serializers.CharField(max_length=100) preferredtime = serializers.DateTimeField() car = TableEvs() pref_pay_mode = serializers.CharField(max_length=100) Next I need to check if json body in post request has matching data as defined in TableEvs Class : class TableEvs(models.Model): # uid = models.BigIntegerField() ev_uid = models.IntegerField() company = models.CharField(max_length=100) model = models.CharField(max_length=100) can someone confirm if its possible ? -
How to handle shopify admin API calls rate limit in django app
I have a shopify app that built in django app with some celery workers, each worker can send a lot of request to shopify and the types of request have several priority in my app, now I want to build a shared priority queue between workers for each store to handle shopify rate limit and priority: celery worker 1: import shopify import time # update more than 1000 of variants for variantId in variantIds: time.sleep(0.5) with shopify_session(store.domain, store.token): shopifyVariant = shopify.Variant.find(variantId) # here some cahnges on variant shopifyVariant.save() celery worker 2: import shopify import time # update store info for store in stores: time.sleep(0.5) with shopify_session(store.domain, store.token): shopInfo = shopify.Shop.current() # update shop info in app database web app: class TagList(APIView): @generate_shopify_session def get(self, request): try: data = ShopifyGraphQl().tags() except BaseException as err: return JsonResponse({"message": str(err), 'success': False}) return JsonResponse({"data": data, "success": True}) These are a few examples of api calls in my app that can be called in one second and shopify will response with 429 too many request status code What is the best architecture for implement queues and handle the shopify rate limit? -
Readiness and liveness probes for application with dependencies (DB, Celery, RabbitMQ)
Imagine there is a Django application. The application dependencies: DB, Celery (workers, beat), RabbitMQ (as a broker for Celery). If with liveness probe it is more or less clear (if the liveness probe did not pass, it restarts pod), then with readiness probe there is no full understanding. They write that readiness probes determine whether the container is ready to accept traffic. In this regard, the following questions arise: For the application configuration described above (with dependencies), what would a readiness probe look like? Will it be an endpoint that checks the availability to the database, RabbitMQ, the health of the Celery workers? If the readiness test is complex (checking the availability of the database, RabbitMQ, Celery workers), then what will Kubernetes do if, for example, RabbitMQ becomes unavailable? Because all containers work with the same RabbitMQ, it makes no sense to switch traffic to another pod. -
How to get return from celery task in Django to view?
I am processing a large file using celery task in my Django app. I have an APIView in which when it receives a POST, it will trigger the process. In the celery task, I create a model instance and save. How am I going to receive it back to the APIView so that I can serialize the instance. For simplicity. This would be my APIVIew. # views.py class RequestFile(APIView): def post(self, request): ... image = long_running_function.delay( request.user.id, request.data ) ... # how to get the return from the long_running_function? # return model serializer In my celery task. I am creating a model instance that I would like to de-serialize in my view. # models.py class Image(models.Model): name = models.CharField(max_length=50, blank=True) ... # tasks.py @shared_task def long_running_function(user, data): image = Image.objects.create() ... return image # can I return the model instance here? Is there a function where I can know when the function is done, and return the model instance or the key/id of the instance created? -
Djagno override_settings decorator not respected by DRF Serializer
In my Django settings I've defined a settings var like EXTRA_METADATA_ENABLED = os.getenv("EXTRA_METADATA_ENABLED", False) My test tries to override this by use of override_settings decorator @override_settings(EXTRA_METADATA_ENABLED="Dog") def test_serializer_metadata_deferred_behavior(self): serializer = ResourceBaseSerializer(self.layer) metadata_field = vars(serializer.__class__)['_declared_fields'].get('metadata') self.assertEqual(metadata_field.deferred, True) When I check the var in ResourceBaseSerializer if getattr(settings, "EXTRA_METADATA_ENABLED", False): print("I am here") print(settings.EXTRA_METADATA_ENABLED) else: print("I am there") print(settings.EXTRA_METADATA_ENABLED) # False It prints I am there. False Where I would expect Dog. Can someone shed light into what is going on? From my understanding the Serializer class should respect the settings var, but it looks ther Serializer class is loaded differently and using the settings file. -
How to create views and extend basic Django admin templates?
SyntaxError: closing parenthesis ']' does not match opening parenthesis '{' on line 56 PS D:\djangoProjetcs\usercase> -
Import "channels.auth" could not be resolved
i m trying to create a real time chat app i m following this tutorial https://www.youtube.com/watch?v=cw8-KFVXpTE&list=LL&index=4&t=293s i can't import channels to my project i used these: 'python -m pip install -U channels' i added channels to my apps settings file enter image description here i installed channels and reinstall it i followed another tutorials -
Django admin search function in GenerifForeignkey field with Content_object relation
I am trying to build an admin page that lets admins search through 2 fields of the model "SeasonalitiesCalculated". The fields for my search are called "fruit" and "object_id". "fruit" is a Foreignkey field and returns the "name" field of the corresponding fruit. "object_id" is Genericforeignkey field that sometimes points at a UUID in a model called "Countries" (with a "country_name" field: Germany) and sometimes points at a UUID in a model called "AdminZones" (with an "admin_zone_name" field: California) The problem now is that django seems to not have any standard way of searching through GenericForeignkeys. So I tried defining a search function like this: class SeasonalitiesCalculatedAdmin(admin.ModelAdmin): list_per_page = 20 def country_or_admin_zone_name(self, obj): return obj.country_or_admin_zone_name() country_or_admin_zone_name.short_description = 'Country or Admin Zone' def search_field(self, obj): return obj.search_field() list_display = ('fruit', 'country_or_admin_zone_name', 'content_type', ...) search_fields = ('fruit__fruit_name', 'search_fields') the admin page itself works and it also shows the country or admin zone names and other foreignkey related fields properly since I specified this in the SeasonalitiesCalculated model like this class SeasonalitiesCalculated(LoggingMixinSeasons, Basemodel): fruit = models.ForeignKey('IngredientOriginals', on_delete=models.PROTECT, related_name='%(class)s_related_ingredient_original') content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.UUIDField(default=uuid.uuid4, editable=False) content_object = GenericForeignKey('content_type', 'object_id') ... class Meta: managed = True db_table = 'seasonalities_calculated' verbose_name_plural = 'Seasonalities Calculated' … -
How to save tem file in my system with python
i try to add geometry layer to my gis app from shb layer i use Django for doing that and for uploading file i use serializer FileField now my main question is How can i save temporary file to my system in python is there any way to do that? if there is please help me about that -
Job Portal in Django
Recently, I started working on a job portal project on Django. In the project, I need to create a registration form for multiple types of users. So, please someone suggest if should I create a stored procedure for executing repeated tasks and use that stored procedure in Django? Or is there any way I can reduce code repetition in Django? It will be better if someone can give example as well... -
Multivaluedict key error wventhough i have set name to input field
I have made a form and set method=post and while taking request.post['name'] to a variable MultiValueDictKeyError is Coming why is that ? <form action="verify_user" method="post"> {% csrf_token %} <input required type="text" placeholder="Name" name="name"><br><br> <input required type="password" placeholder="Password" name="password"><br><br> <input required type="passord" placeholder="Confirm password" name="confirm_password" id=""> <br><br> <br><br><h1>{{ messages }}</h1> <button type="submit">Create</button> </form> this is my form ------ def verify_user(request): inputname = request.POST['name'] inputpass = request.POST['password'] inputconfirmpass = request.POST['confirm_password'] if not inputpass == inputconfirmpass: messages.info(request,"Passwords don't match") else: messages.info(request,"Passwords match") return redirect('/verify_user') this is my function in views.py ------------- MultiValueDictKeyError at /verify_user 'name' Request Method: GET Request URL: http://127.0.0.1:8000/verify_user Django Version: 4.1.2 Exception Type: MultiValueDictKeyError Exception Value: 'name' this is the error -------- -
TemplateDoesNotExist at /blog/create/
Not sure if its a typo or not... I don't understand why I am getting this error: enter image description here getting TemplateDoesNotExist error? weird because when I click on create post it takes me to ".../blog/create/" can someone help please! " base.hmtl ''' This is the Title {% include 'snippets/header.html' %} <style type="text/css"> .main{ min-height: 100vh; height: 100%; } </style> <div class="main"> {% block content %} {% endblock content %} </div> {% include 'snippets/footer.html' %} **create.html (inside blog/Template/blog) ** {% extends 'base.html' %} {% block content %} <p>Create a new blog...</p> {% endblock content %} ** urls.py (inside blog folder)** from django.urls import path from blog.views import( create_blog_view, ) app_name = 'blog' urlpatterns = [ path('create/', create_blog_view, name="create"), ] urls.py (in mysite folder) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from personal.views import ( home_screen_view, ) from account.views import ( registration_view, logout_view, login_view, account_view, ) urlpatterns = [ path('admin/', admin.site.urls), path('', home_screen_view, name="home"), path('register/', registration_view, name="register"), path('blog/', include('blog.urls', 'blog')), path('logout/', logout_view, name="logout"), path('login/', login_view, name="login"), path('account/', account_view, name="account"), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py (inside blog) from django.shortcuts import render from blog.models import … -
Django nested query in From clause
Is there any way to construct a query like the following using Django ORM? SELECT * from ( SELECT r1 from table_name ) temp; -
Django Rest allauth Keycloak dj-rest-auth authentication PKCE code verifier not specified
I'm trying to retrieve access and refresh token from django rest framework(simple jwt) through keycloak authentication. I extended dj-rest_auth.registration.views SocialLoginView for retrieving the token, but I'm getting an error like allauth.socialaccount.providers.oauth2.client.OAuth2Error: Error retrieving access token: b'{"error":"invalid_grant","error_description":"PKCE code verifier not specified"}' please forgive me if there is any misunderstanding in my code and please help. -
My Html Table footer doesn't render correctly
I'm trying to create a simple table. I would like a footer with only one cell but I don't know why it's divided in two. Any idea? <table class="table-cart-view-producer"> <thead> <tr> <th>Produit</th> <th>Quantité</th> <th>Prix</th> </tr> </thead> <tfoot> <tr> <th> Prix Total du Panier : <strong>{{cart_price}}€</strong></th> </tr> </tfoot> <tbody> {% for item in cartitems %} <tr> <td>{{item.stock_item.product_stockitem.name}}</td> <td>{{item.quantity}} {{item.stock_item.product_stockitem.unit}}</td> <td>{{item.get_total_price}}€</td> </tr> {% endfor %} </tbody> </table> It renders this way: -
Celery Django: Resource temporarily unavailable: 'celerybeat-schedule'
Have some problems with setting celery a schedule Trying to create celerybeat-schedule with command: "celery -A my_app beat -l info" It has infinity starting msg: LocalTime -> 2023-01-30 14:36:49 Configuration -> . broker -> amqp://guest:**@192.168.101.36:5672// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2023-01-30 14:36:49,493: INFO/MainProcess] beat: Starting... When im trying to call command: "celery -A my_app beat" I got an error: [2023-01-30 14:36:37,316: ERROR/MainProcess] Removing corrupted schedule file 'celerybeat-schedule': error(11, 'Resource temporarily unavailable') Traceback (most recent call last): File "/home/knefedov/PycharmProjects/unica_b2b_1/venv/lib/python3.10/site-packages/celery/beat.py", line 533, in setup_schedule self._store = self._open_schedule() File "/home/knefedov/PycharmProjects/unica_b2b_1/venv/lib/python3.10/site-packages/celery/beat.py", line 523, in _open_schedule return self.persistence.open(self.schedule_filename, writeback=True) File "/usr/lib/python3.10/shelve.py", line 243, in open return DbfilenameShelf(filename, flag, protocol, writeback) File "/usr/lib/python3.10/shelve.py", line 227, in __init__ Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback) File "/usr/lib/python3.10/dbm/__init__.py", line 95, in open return mod.open(file, flag, mode) _gdbm.error: [Errno 11] Resource temporarily unavailable: 'celerybeat-schedule' celery.py import os from celery import Celery from django.conf import settings from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') app = Celery('unica_b2b', broker_url='some_ip') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.beat_schedule = { 'add-update-every-5-minutes': { 'task': 'authentication.tasks.create_counter_party', 'schedule': 300.0, 'args': (16, 16) }, } app.conf.timezone = 'UTC' -
Django - Problem with Model Manager - Query
I'm still a beginner and I'm stuck in a challenging spot for me. I can't get data from a foreign key table to be inserted "correctly" into a column of a ListView. I basically want to create a list view of a table (FeatureFilm). This also works. But in one column I get information from another table and here I get data, but not the one that belongs to the particular table row. Here are my models. The table I want to show is "FeatureFilm" model. This model is inherited from my base Project class "ProjectBaseModel". Then there is another table "CompanyInvolved Model". This is attached to the FeatureFilm table with a foreign key (feature_id). So movies are stored (FeatureFilm) and different companies are involved in the creation process of the movies. (CompanyInvolved) class ProjectBaseModel(models.Model): title = models.CharField("Titel", max_length=100, blank=False, unique=True) leading_postproduction_id = models.ForeignKey( Company, verbose_name="Federführende Postproduktion", on_delete=models.SET_NULL, blank=True, null=True, ) phase = models.CharField(choices=post_phase, max_length=30, blank=True, null=True) former_title = models.CharField("Titel, ehemalig", max_length=100, blank=True) title_international = models.CharField( "Titel, international", max_length=100, blank=True, null=True, unique=True ) class FeatureFilm(ProjectBaseModel): class Meta: verbose_name = "Kinofilm" verbose_name_plural = "Kinofilme" ordering = ["title"] class ProductionManager(models.Manager): def get_production(self): return ( super() .get_queryset() .filter(company_role="Produktion", is_production_list=True) .values_list("company_involved__name") ) class CompanyInvolved(models.Model): … -
make mutualTLS between microservices (Django, Fastapi)
I have microservices on Django and FastAPI. I want to make mutualTLS between these services. When I send request from Django project to FastApi project for payment (need to check certificate in FastApi project from Django project) and then FastApi project send request for notify about success or not payment to Django project (need to check certificate in Django project from FastApi project). Like this :) I've tried a lot to implement MutualTLS between Django and FastAPI. -
Bundle django postgres nginx gunicorn docker in real projects [closed]
подскажите пж-ста как в реальных проектах используют связку django postgres nginx gunicorn docker? Т.е, к примеру, БД устанавливают на один сервер и к ней подключаются (мб тоже в докер контейнер устанавливают), nginx в докер, gunicorn тоже в докер, все отдельно, в потом как то связывают или как то иначе... -
Django Model Formset from ManyToMany not accepting queryset
I have my model called Game that has a ManyToMany field consoles = models.ManyToManyField('Console', through='GameConsole') That ManyToMany has some additional attributes class GameConsole(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) console = models.ForeignKey(Console, on_delete=models.CASCADE) released = models.DateTimeField exclusive = models.BooleanField(default=False) I have a page where I want to create/edit those relations. #forms.py class GameConsoleForm(ModelForm): class Meta: model = GameConsole fields = ['console', 'released', 'exclusive'] #to prevent the submission of consoles with the same id (taken from django topics forms formsets) class BaseGameConsoleFormSet(BaseFormSet): def clean(self): """Checks that no two alias have the same name.""" if any(self.errors): # Don't bother validating the formset unless each form is valid on its own return console_ids = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue console= form.cleaned_data.get('console') if console in console_ids: raise ValidationError("Consoles in a set must be different.") console_ids.append(console) NewGameConsoleFormSet = modelformset_factory(GameConsole, form=GameConsoleForm, formset=BaseGameConsoleFormSet, extra=1, can_delete=True) GameConsoleFormSet = modelformset_factory(GameConsole, form=GameConsoleForm, formset=BaseGameConsoleFormSet, extra=0, can_delete=True) The creation of multiple GameConsole's works fine. The problem is on the edition. On the views, when I do the following: formset = GameConsoleFormSet(queryset = game_consoles) I get the following error __init__() got an unexpected keyword argument 'queryset' which is strange, since I already used this logic with another model (normal table, … -
Django Rest Framework - Why is serializer.data giving me an empty result set but printing the serializer shows me the data
I have created a view to search posts based on their body text. I added a breakpoint to the view and I tested it with mutliple search terms and it works. The problem I have is when I do a print(serializer) in the console then I see the data of all the posts it found. But doing a print(serializer.data) gives me body:null in the data object in the front end console and an empty dictionary in the back end console. Why am I getting body: null? Here is the response in the console for print(serializer): SearchSerializer(<QuerySet [<Post: This is a post>, <Post: This is another post>, <Post: Post THREE>, <Post: Post ONE>, <Post: Post ONE by the user>, <Post: Post TWO by the user>]>): body = CharField(allow_blank=True, allow_null=True, label='Content', max_length=5000, required=False, style={'base_template': 'textarea.html'}) Here is the view: class SearchPosts(APIView): permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): term = request.data.get("term") posts = Post.objects.filter(body__search=term) serializer = SearchSerializer(posts) breakpoint() return Response(serializer.data, status=HTTP_200_OK) Here is the serializer: class SearchSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ 'body' ] Here is the post model: class Post(models.Model): body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posts") published … -
Django URL dispatcher - Try next view
Alright, let me give you guys an example; We have the following url configuration in Django. Django will try to match the url with the rules down below. Once it finds a match, it will use the appropriate view and lookup the object in the model. The thing is, once it finds a match in the URL pattern, it will match the view. But once the object in the view can't be found, it will return a page not found (404) error. #urls.py from django.urls import path from . import views urlpatterns = [ path('articles/<slug:category>/<slug:editor>/', views.articles_by_editor), path('articles/<slug:category>/<slug:theme>/', views.articles_by_theme) ] We have the following url patterns, we can sort articles either by the editor or by theme. We do this to create a logical url structure for SEO purposes. Is their any way we can redirect to another view once the object isn't found? Can we modify the dispatch method to return to the url patterns and find the following matching rule? Your help will be much appriciated. Kevin -
Django, Choices to Serilize
I have choices like this in my choices.py MATH_CHOICES_TYPE = ( ('1', 'test1'), ('2', 'teste2'), ('3', 'test3'), ('4','test4') ) I want to get result like this as json from APIVIEW using get method Is there any solution? Thanks { "MATH_CHOICES_TYPE": [ { "value": "1", "display_name": "test1" }, { "value": "2", "display_name": "test2" }, { "value": "3", "display_name": "test3" }, { "value": "4", "display_name": "test4" } ] }