Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is the server running on host "localhost" (127.0.0.1) and accepting web-1 TCP/IP connections on port 5432?
I have made a Django project with a postgresql backend and am trying to containerize it. This is my Dockerfile: Dockerfile This is my docker-compose.yml file: docker-compose.yml This is my settings.py within the django project to connect to the db: Settings.py The sudo docker build . command runs without any errors. The error I get when I try to run 'sudo docker compose up' is as follows: Is the server running on host "localhost" (127.0.0.1) and accepting web-1 TCP/IP connections on port 5432? I have confirmed that the postgres server is running: Server active(running) This application also runs without any errors on my local. I had created a network(inventory_network) on which I tried attaching my containers. But one thing I noticed was that whenever I ran the 'compose up' command, it created another network inventory_management_inventory_network automatically to which the containers attached instead of my specified network inventory_network: This is what I got when i ran 'inspect' on both these networks, as I wasn't sure if this was related to the issue: inventory_network inspect inventory_management_inventory_network inspect I have tried everything I know and would really appreciate any inputs. -
How to effectively use PUT and DELETE HTTP methods in Django Class-Based Views?
I'm setting up a CRUD system with Django, using Class-Based Views. Currently I'm trying to figure out how to handle HTTP PUT and DELETE requests in my application. Despite searching the Django documentation extensively, I'm having trouble finding concrete examples and clear explanations of how to submit these types of queries to a class-based view. I created a view class named CategoryView, extending from: django.views.View, in which I implemented the get and post methods successfully. And I want to build my urls like this: New Category: 127.0.0.1:8000/backendapp/categories/create List all Category: 127.0.0.1:8000/backendapp/categories/ Retrieve only one Category: 127.0.0.1:8000/backendapp/categories/1 Etc... However, when I try to implement the put and delete methods, I get stuck. For example : from django.views import View class CategoryView(View): template_name = 'backendapp/pages/category/categories.html' def get(self, request): categories = Category.objects.all() context = { 'categories': categories } return render(request, self.template_name, context) def post(self, request): return def delete(self, request, pk): return def put(self, request): return I read through the Django documentation and found that Class-Based Views support HTTP requests: ["get", "post", "put", "patch", "delete", "head ", "options", "trace"]. link: https://docs.djangoproject.com/en/5.0/ref/class-based-views/base/#django.views.generic.base.View Despite this, I can't figure out how to do it. So I'm asking for your help to unblock me. I looked at the … -
Django ORM, similar queries [duplicate]
Help me remove duplicates please, I’ve already tried everything, documentation, chatGPT, I don’t know how to remove it, it’s just that when I access the .html attribute a new request to the database is generated I'm using django-mailbox, I couldn't specify it because the rating is less than 1500. Models: https://django-mailbox.readthedocs.io/en/latest/_modules/django_mailbox/models.html messagesDB = Message.objects.filter(mailbox=mailbox).select_related('mailbox', 'message_used').prefetch_related(Prefetch('attachments', queryset=MessageAttachment.objects.all(), to_attr='all_attachments')) for message in messagesDB: print(message.html) SELECT ••• FROM "django_mailbox_messageattachment" WHERE "django_mailbox_messageattachment"."id" = 44 LIMIT 21 13 similar queries. **SELECT "django_mailbox_messageattachment"."id", "django_mailbox_messageattachment"."message_id", "django_mailbox_messageattachment"."headers", "django_mailbox_messageattachment"."document" FROM "django_mailbox_messageattachment" WHERE "django_mailbox_messageattachment"."id" = 44 LIMIT 21 13 similar queries.** C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\contrib\staticfiles\handlers.py in __call__(80) return self.application(environ, start_response) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\whitenoise\middleware.py in __call__(124) return self.get_response(request) C:\Users\user\AppData\Local\Programs\Python\Python310\lib\contextlib.py in inner(79) return func(*args, **kwds) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\views\generic\base.py in view(104) return self.dispatch(request, *args, **kwargs) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\contrib\auth\mixins.py in dispatch(73) return super().dispatch(request, *args, **kwargs) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\contrib\auth\mixins.py in dispatch(109) return super().dispatch(request, *args, **kwargs) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\views\generic\base.py in dispatch(143) return handler(request, *args, **kwargs) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\views\generic\base.py in get(226) context = self.get_context_data(**kwargs) C:\Users\user\Desktop\Задачник\ProjectsDashboard\dashboard\timetable\views.py in get_context_data(2109) messagesDB = self.get_message_telegram(self.mailbox) C:\Users\user\Desktop\Задачник\ProjectsDashboard\dashboard\timetable\views.py in get_message_telegram(2058) print(message.html) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in html(671) self.get_email_object(), 'text', 'html' C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in get_email_object(783) self._email_object = self._rehydrate(flat) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in _rehydrate(683) self._rehydrate(part) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in _rehydrate(683) self._rehydrate(part) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in _rehydrate(687) attachment = MessageAttachment.objects.get( C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\cacheops\query.py in get(327) return qs._no_monkey.get(qs, *args, **kwargs) C:\Users\user\.virtualenvs\dashboard-APxxHYiU\lib\site-packages\cacheops\query.py in _fetch_all(250) return self._no_monkey._fetch_all(self) -
Can't understand how ForeignKey works
I'm designing a model for a company. It has several fields of activity: class Activity(models.Model): title = models.CharField(max_length=255) class Company(models.Model): title = models.CharField(max_length=255) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) And the admin: class ActivityInline(admin.TabularInline): model = Activity class CompanyAdmin(admin.ModelAdmin): inlines = [ActivityInline] But that gives me this error: company.Activity has no ForeignKey to company.Company And I know to fix it I have to do this: class Activity(models.Model): title = models.CharField(max_length=255) company = models.ForeignKey(Company, on_delete=models.CASCADE) class Company(models.Model): title = models.CharField(max_length=255) But the issue is, here the Company is the main model. One company has several activities not the other way around (OneToMany) so the ForeignKey should be defined in the Company model not the Activity. Or there's something I don't understand here? -
Must I create a model only within an app in Django, not in the project directly?
I created a project like so: $ cd dj-container $ django-admin startproject core . $ django-admin startapp app1 This means that core.apps does not exist, but app1.apps does. I want to create models under core, not app1 (some models that are nor app specific, but are project specific). I created a Country model under core, and on running makemigrations, I get this error: RuntimeError: Model class core.models.Country doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Do I have to add core in INSTALLED_APPS? And then perhaps creaate core.apps and create the app label. I am essentially making the core an app, and I vaguely think this is a wrong approach. Or do I just add an explicit app_label in the Model? Or should I create a separate app just for my common tables? -
Facebook Pixel popup not working on https but working when i am removing ssl its working fine
I have developed the website (http://littlestepwelfarefoundation.com/) on Django, taken domain from Godaddy, hosted on EC2 windows server and took ssl certificate from ACM only. When I am securing my site and routing http to https, facebook pixel is not firing, but when I am removing SSL and trying to access without https, it gets fired. -
Difference between regular def and lambda for reversing a url in django test
Consider the following two examples and explain to me why they are different (they look the same to me but the lambda does not work as expected) Using the lambda, I keep getting the following error: TypeError: SurveyConversationViewSetTestCase.setUpTestData.<locals>.<lambda>() missing 1 required positional argument: 'pk' nested url /api/surveys/<survey_pk>/survey-conversations/<pk>/ survey_conversations.views.SurveyConversationViewSet survey-conversations-detail Test class SurveyConversationViewSetTestCase(UserSetupMixin, APITestCase): @classmethod def setUpTestData(cls): super().setUpTestData() cls.update_url = lambda self, pk: reverse( "survey-conversations-detail", kwargs={"survey_pk": cls.survey.pk, "pk": pk} ) def get_update_url(self, pk): return reverse( "survey-conversations-detail", kwargs={"survey_pk": self.survey.pk, "pk": pk}, ) # this fails def test_with_lambda(self): response_create = self.client.post( self.create_url, {"participant_id": self.participant.pk} ) conversation_id = response_create.data["conversation_id"] self.client.patch(self.update_url(str(conversation_id)),{"answer": "Walking"}) # this passes def test_with_def(self): response_create = self.client.post( self.create_url, {"participant_id": self.participant.pk} ) conversation_id = response_create.data["conversation_id"] update_url = self.get_update_url(conversation_id) response = self.client.patch(update_url, {"answer": "Walking"}, format="json") -
I try to ,make a fixture in Django, using dumpdata, and instead of letters i have symbols
when i try do to a fixture in Django, i use dumpdata, and when I create a JSON file, where the name is, instead of letters there are some symbols, I use this command python manage.py dumpdata goods.Categories > fixtures\goods\cats.json my json file after, is looking like this { "model": "goods.categories", "pk": 4, "fields": { "name": "┬ёх ЄютрЁ√", "slug": "all" } -
Can't access sessionid and csrftoken on Chrome
I am struggling. Right now I am trying to figure out this block. Maybe i havent looked hard enough but I have been at this for a whole entire day. Figured this would be my last resort. Right now I am trying to send the sessionid cookie (from DRF) back to Django (from React) in order to keep track of some data. The user does not have to be authenticated for this to work. When a user makes a request and there is no session key, I populate a new session with some data and return a response to the user. FROM MY UNDERSTANDING, the sessionid cookie is sent along with the response from DRF which is stored in the browser cookers. That way, subsequent requests send those cookies (using "credentials: include") back to Django so that we can keep track of a session. Great. The problem is that: when I create a new session and make another request, it creates a new session instead of accessing the one that was initially made. This is because the session_key is None when I try to access it in the request on the backend which leads the view to create a new … -
Is there a good way to manage very long translation texts in Django?
For Django i18n, it is common to use makemassages and compilemessages to create django.po and django.mo files. It works very well for translating short text fragments, and in fact I've been able to i18n almost all of my website using it. Usually, however, a website is not just fragmented text, but has several pages containing very very long sentences, such as "Terms of Use," "User Guide," and so on. If we try to translate them using Django's features (trans, blocktrans), the po file become hard to manage. It seems silly to me to manage these fragmented texts and very long sentences in one po file. So I have a question. Is there any way to split up the po files? It would be a solution if I could create a po file specifically for pages containing such long sentences, but I couldn't find such an option in the Django manual. Or is there another better way? I'd like to avoid having separate template files for each language and using {% if %} on the templates to display them. (but unfortunately, that's actually how I'm dealing with it now) I checked the Django manual; I also checked the gettext manual. But … -
Is it possible to pass two variables in a Django redirect?
I am trying to create dynamic URLS in Django with two variables like the ones below: path('fin-data-add/<str:fintype>/fin-data-update/<str:pk>', views.finDataUpdate, name='fin- data-update'), path('fin-data-add/\<str:fintype\>/fin-data-delete/\<str:pk\>', views.finDataDelete, name='fin-data-delete') path('fin-data-add/\<str:fintype\>/fin-categories/fin-categories-delete/\<str:pk\>', views.finCatDelete, name='fin-categories-delete') And I am trying to pass these variables in my views.py in the way below: @login_required(login_url='home:login') def finDataUpdate(request, fintype, pk): expense = Expenses.objects.get(id=pk) form = ExpenseForm(instance=expense) if request.method == 'POST': form = ExpenseForm(request.POST, instance=expense) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() return redirect('boost:fin-data-update', kwargs={'fintype': fintype, 'pk': pk}) database = Expenses.objects.all() fin_type = 'Expense' fin_type_plural = 'Expenses' context = {'form': form, 'database': database, 'fin_type': fin_type, 'fin_type_plural': fin_type_plural} return render(request, 'boost/fin-data-update.html', context) But I am getting the error below: NoReverseMatch at /boost/fin-data-add/expense Reverse for 'fin-data-update' with arguments '(45,)' not found. 1 pattern(s) tried: ['boost/fin\\-data\\-add/(?P<fintype>[^/]+)/fin\\-data\\-update/(?P<pk>[^/]+)\\Z'] Is it possible to pass two variables like I am trying? -
How can I implement a basic program-wide translation function into my Django project?
I'm making something for my Computer Science coursework which is a POS system running on Django. Here's my repo: https://github.com/Ashaz/django_point_of_sale Background Info So basically, the program itself isn't reviewed by the examiners. However, I need to evidence that the features I have are working by recording a short video of my program in use. It doesn't matter if the actual features don't perform the FULL intended purpose. For example, in this program it says "Sales" but because I'm catering mine towards the catering industry, ideally it would say "Orders". I've been allowed to use a fork of the original project. My Problem So, the main goal of my project is to make it so that the user can select a language to translate into and the program then translates the page into that language. The thing is I can just include the Google translate form on the page but I need to go a step further to evidence I've actually done some work, meaning I need to use APIs or something. The translation does not need to be 100% accurate but rather show an attempt was made; there's limitations like being a student and studying subjects which allow justification. I … -
Python opentelemetry wsgi usage with gunicorn / Application Insights
I have the below setup working perfectly in development mode in my django application, so when I run python manage.py runsslserver the application reports perfectly to Application Insights. from azure.monitor.opentelemetry import configure_azure_monitor from django.conf import settings as my_settings def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my.settings') # Configure OpenTelemetry to use Azure Monitor with the specified connection string AZ_OPENTELEMETRY_CONNECTION_STRING = impact3_settings.AZ_OPENTELEMETRY_CONNECTION_STRING configure_azure_monitor( connection_string=AZ_OPENTELEMETRY_CONNECTION_STRING, ) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() However, when I move this into production, we're utilizing gunicorn and wsgi, so, manage.py isn't ever running. I've found a way to to add OpenTelemetryMiddleware to the wsgi file, but have no idea how/where to call the configure_azure_monitor to record every request. What am I missing? import os from django.core.wsgi import get_wsgi_application from opentelemetry.instrumentation.wsgi import OpenTelemetryMiddleware os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my.settings') application = get_wsgi_application() application = OpenTelemetryMiddleware(application) -
Django Model Permissions. Why is this hard?
Django creates permissions for every model you make, such as: can_view_{model_name} can_add_{model_name} can_edit_{model_name} Out of the box, these are only applicable to Django Admin. Ok well if I want to apply them at the model level, why can't I do: class MyModel(models.Model) def can_view(self, user): if user.has_perm('my_app.can_view_my_model'): return True return False And then any time the ORM tries to lookup that model, it has to check the permission first. Instead, I have to go into each View and manually check: class MyModelDetail(APIView): @transaction.atomic def get(self, request): try: if not request.user.has_perm("my_app.can_view_my_model"): raise APIException("You do not have permission to view this model") And repeat that across all views that look up my model. Is there an easier way? -
How to generate file in MEDIA_ROOT in Django?
In my view I have a function that generates a file but does not return anything. I want the file to be generated in a specific folder in MEDIA_ROOT and saved in my models but I'm not sure how exactly to go about doing it. Here is the relevant section of my view: writer = get_writer(output_format, output_dir) This function generates a file in the stated directory. I want to save it to a specific directory relevant to my MEDIA_ROOT. Here is the relevant section of my settings.py file: MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') The destination directory, for example, can be media/destination_directory but I'm not sure how to write the path relative to MEDIA_ROOT -
RuntimeError('Event loop is closed') in Django Rest Framework with google generative ai
I am using google generative ai in django rest framework. I send a request in my backend with adrf (async views package), I can process my answer with Gemini pro, but when I send other request I get this error: raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed [11/Apr/2024 15:20:49] "POST /api/chatbot/ HTTP/1.1" 500 165320 C:\Users\User\Documents\Python\chatbot-django-entrevista\apps\chatbot\views\gemini_views.py changed, reloading. sys:1: RuntimeWarning: coroutine 'UnaryUnaryCall._invoke' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback Watching for file changes with StatReloader Performing system checks... This is my code: import google.generativeai as genai genai.configure(api_key=settings.GOOGLE_API_KEY) @async_api_view(['POST']) async def post_message(request): """ This view post a message """ model = genai.GenerativeModel(settings.MODEL) messages = [ {'role':'user', 'parts': ["Briefly explain how a computer works to a young child."]} ] response = await model.generate_content_async(messages) print(response) return Response({'msg':'text'}) -
Why I can't start Django web site with docker?
I have a Django web app and I need to launch it with docker. I created two images: one for Django and another for postgresql. It successfully builds but during the composing up shows the problem that django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module. Seems like docker didn't install psycopg2 from requirements.txt. Dockerfile: # Here I'm creating an image for Django. FROM python:3.10.0-alpine COPY requirements.txt /requirements.txt COPY movies_admin /movies_admin WORKDIR /movies_admin EXPOSE 8000 RUN apk add postgresql-client build-base postgresql-dev RUN pip install -r requirements.txt docker-compose.yml services: django: build: context: . ports: - "8000:8000" volumes: - "./movies_admin:/movies_admin" environment: - DB_HOST=database - POSTGRES_DB=movies_database - POSTGRES_USER=app - POSTGRES_PASSWORD=123qwe command: sh -c "python3 manage.py runserver 0.0.0.0:8000" depends_on: - database database: image: postgres:16 environment: - POSTGRES_DB=movies_database - POSTGRES_USER=app - POSTGRES_PASSWORD=123qwe requirements.txt asgiref==3.8.1 autopep8==2.1.0 black==24.3.0 click==8.1.7 Django==5.0.4 django-split-settings==1.3.1 flake8==7.0.0 mccabe==0.7.0 mypy-extensions==1.0.0 packaging==24.0 pathspec==0.12.1 platformdirs==4.2.0 psycopg2==2.9.9 psycopg2-binary==2.9.9 pycodestyle==2.11.1 pyflakes==3.2.0 python-dotenv==1.0.1 sqlparse==0.4.4 tomli==2.0.1 typing_extensions==4.11.0 -
Django- How to use django-silk to work in running tests
I use the django-silk to profile the APIs of my Django project (Django + DRF). Currently, I call APIs in the browser (using DRF browsable API) and then I can see the API profiling data in the silk. When I run the test command, it doesn't capture requests and responses and therefore it doesn't create any profiling data to show. Is there a way to force the silk to work in test environment? My idea is to instead of calling APIs one by one in the browser and then check the silk, only run the tests and then see the profiling data after tests finished. -
Is it possible to use Hug with Django?
I'm a Django developer and recently stumbled onto the Hug framework... Then I decided to give it a shot. But usually when you talk about building RESTful APIs with Django you usually use the Django Rest Framework (DRF)... -
Dropzone.js does not post files in queue, only post files with JavaScript is incorrectly formatted
I have a Django project that uses Dropzone to upload multiple files to a project a user has created. All of this is within the same instance (project is created alongside file uploads), so I am using autoProcessQueue: false and running dropzone.processQueue() once the rest of the form data has been added. I have a malformatted javascript file that ends up working. Files are posted and I can access them through <MultiValueDict: {'file': [<InMemoryUploadedFile: <img_name>.jpg (image/jpeg)>]}>. This 'works' but I cannot upload multiple files. My correctly formatted javascript doesn't return anything. When I drop a file into the dropzone space in the html, the preview shows but now file is loaded. When I POST the form, I get this in the output for dropzone: <MultiValueDict:[] Why is my bad JS partially functional, but my proper JS is not capturing any file uploads? BAD but Working javascript.js for 1 file in dropzone dropzonePreviewNode && (dropzonePreviewNode.id = "", previewTemplate = dropzonePreviewNode.parentNode.innerHTML, dropzonePreviewNode.parentNode.removeChild(dropzonePreviewNode), dropzone = new Dropzone(".dropzone", { headers: { 'X-CSRFToken': csrftoken }, autoProcessQueue: false, url: "create", method: "post", uploadMultiple: true, previewTemplate: previewTemplate, previewsContainer: "#dropzone-preview", acceptedFiles:'.jpg', }) dropzone.on('success', dropzone.processQueue.bind(dropzone)); Correct JS, but not working - Causes Broken Pipe: dropzonePreviewNode && (dropzonePreviewNode.id = "", … -
jango Cannot resolve keyword 'display_data' into field. Choices are: choosenum, displays, id, puplish_date, users v2
hi i have a django project rise the error above this is models.py class Display(models.Model) : url=models.URLField(unique=True) text = models.CharField(max_length=150) class Display_Data(models.Model) : displays = models.ManyToManyField(Display,related_name='display_data') users= models.ManyToManyField(User) choosenum=models.IntegerField() puplish_date =models.DateTimeField(default=datetime.now) and this is views.py check_url_exists(url_to_check): try: countArray= [] # محاولة استرداد سجل بناءً على الرابط المعطى display_obj = Display.objects.get(url=url_to_check) for i in range(1, 6): # حساب عدد السجلات where choosenum = i count = Display_Data.objects.filter(display_data__url=url_to_check, choosenum=i).count() print(count)# إضافة عدد السجلات إلى القائمة countArray.append(count) return countArray # الرابط موجود في قاعدة البيانات except Display.DoesNotExist: countArray= [0,0,0,0,0] return countArray def display_video(request, url): # تشكيل الـ URL الكامل لإطار الفيديو على YouTube embed_url = f"https://www.youtube.com/embed/{url}" full_url = f"https://www.youtube.com/watch?v={url}" soup = BeautifulSoup(requests.get(full_url).content, "html.parser") title = soup.title.text # استخدم نموذج "display_data" countArry=check_url_exists(embed_url) # استخدم "Count" لحساب عدد السجلات # طباعة النتيجة this is templete who is include with the templete above <div class="container mt-5"> <div class="d-flex justify-content-start">> <!-- زر "نجحت" --> <button type="submit" name="CHOOSE" value="1" class="btn btn-success mr-2">{{carry_0}} نجحت</button> <!-- زر "فشلت" --> <button type="submit" name="CHOOSE" value="2" btn btn-danger mr-2">{{carray_1}}فشلت</button> <!-- زر "تحتاج إلى مال" --> <button type="submit" name="CHOOSE" value="3" class="btn btn-warning mr-2">تحتاج إلى مال{{carray_2}}</button> <!-- زر "تحتاج إلى أدوات" --> <button type="submit" name="CHOOSE" value="4" btn btn-info mr-2">{{carray_3}}تحتاج إلى أدوات</button> <!-- زر "مؤجل" --> … -
Loop in a Django template simple_tag returning a dictionary
When using a simple template tag that returns a dictionary: @register.simple_tag def get_types(): return { "item1": "Foo", "item2": "Bar", } This doesn't print any column: {% for type in get_types.values %} <th>{{ type }}</th> {% endfor %} While this does: {% get_types as types %} {% for type in types.values %} <th>{{ type }}</th> {% endfor %} Is there a way to make it work without having to put the temporary variable {% get_types as types %}? Most questions I found on StackOverflow or in forums are from 2018 or older. I'm wondering if there is a cleaner way to do this 6 years later as I'm not a fan of temporary variables. -
Django newbie started an hour ago
here Why is this happening? I just copied whatever this guy explained and tried mapping the URLs to views but my homepage ended like the image. Please help me and explain however you can. nothing yet cause i am still learning and this is my first time. please dont judge me -
How to use Celery as priority queue?
I use Celery to process background jobs that use a blocking API for a Django web app. Since the API can only process one job at a time, I also use a lock (implemented with Redis) to ensure that only one job is running at a time. I have jobs with different priorities, and I wonder if I need to implement the sorting by priority myself, or if celery or Redis already provides a priority queue, which might also be more robust against race conditions. Best would be if I also had the option for the current job to check if something with a higher priority is in the queue and then decide if it should cancel the current operation and put it back in the queue. -
How do i get this filter class view to work since first two views are working?
Just started learning django. I can't get the filtering for this to work: views.py: class BlogPostList(APIView): def get(self, request, format=None): title = request.query_params.get("title", "") if title: blog_posts = BlogPost.objects.filter(title_icontains=title) else: blog_posts = BlogPost.objects.all() serializer = BlogPostSerializer(blog_posts, many=True) return Response(serializer.data, status=status.HTTP_200_OK) urls.py: urlpatterns = [ path("blogposts/", views.BlogPostListCreate.as_view(), name="Blogpost-view-create"), path("blogposts/<int:pk>/", views.BlogPostRetrieveUpdateDestroy.as_view(), name="update"), path("blogposts/", views.BlogPostList.as_view(), name="Filter"), ] the first two views work. models.py: from django.db import models # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=100) content = models.TextField() published_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title here's the full views.py code: from django.shortcuts import render from rest_framework import generics, status from rest_framework.response import Response from .models import BlogPost from .serializers import BlogPostSerializer from rest_framework.views import APIView # Create your views here. class BlogPostListCreate(generics.ListCreateAPIView): queryset = BlogPost.objects.all() serializer_class = BlogPostSerializer def delete(self, request, *args, **kwargs): BlogPost.objects.all().delete() return Response(status=status.HTTP_204_NO_CONTENT) class BlogPostRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): queryset = BlogPost.objects.all() serializer_class = BlogPostSerializer lookup_field = "pk" class BlogPostList(APIView): def get(self, request, format=None): title = request.query_params.get("title", "") if title: blog_posts = BlogPost.objects.filter(title_icontains=title) else: blog_posts = BlogPost.objects.all() serializer = BlogPostSerializer(blog_posts, many=True) return Response(serializer.data, status=status.HTTP_200_OK)