Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
send template data from signal in django
As soon as the django user_logged_in signal works, I want to send data to my template at that moment.I need to check if my signal is working. from django.contrib.auth.signals import user_logged_in @receiver(user_logged_in) def post_login(sender, user, request, **kwargs): isLogged = True # base.html I want to send this to 'isLogged= True' base.html I don't know if I can do this with context processor.I just want to send data to base.html file as soon as user logs in -
Representing Django M2M data export in a CSV
The problem I am trying to solve is to export all the entries of a Django model as CSV. The field names are supposed to be headers, with each row having an appropriate value under each column. The challenge here is that the model has a few M2M relationships. Each associated M2M model has multiple fields in it. I have added a subset of the main model and some related models below: class Semester(TimeStampedModel): title = models.TextField() uuid = models.UUIDField(blank=False, null=False, default=uuid4, editable=False, verbose_name=_('UUID')) class CreditClass(TimeStampedModel): title = models.TextField() category = models.CharField(max_length=32) is_active = models.BooleanField(default=False) credits = models.IntegerField() class Student(TimeStampedModel): name = models.TextField() age = models.IntegerField() active_semesters = models.ManyToManyField(Semester) enrolled_classes = models.ManyToManyField(CreditClass) Each student will have a different count for associated model entries. For example, Student A in the 3rd semester will have an association with 3 Semester objects while a student B in the 5th Semester will have 5. The credit class count is also the same case. Therefore, defining static headers in CSV is difficult, given the data will vary on each row. That said, the only plausible solution in my mind: Export each M2M model data in the form of a list of JSON, dump the list … -
Difficulty converting html page with CSS and images to PDF in Django
I am trying to convert an HTML page which uses quite the bootstrap and styling. I tried everything from reportlab to weasyprint to xhtml2pdf and nothing works! I did not find anything online to help me do this simple task. I even tried looking for paid APIs that do this kind of jobs. What is the best way to achieve this? -
i was trying run a pretrained chatbot but got this error......(link to project file:https://github.com/lukalabs/cakechat) please help me
(chatvirt) PS C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1> python tools/fetch.py Using TensorFlow backend. 2022-05-14 22:49:09.001133: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 Traceback (most recent call last): File "tools/fetch.py", line 15, in <module> from cakechat.dialog_model.factory import get_trained_model File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\factory.py", line 8, in <module> from cakechat.dialog_model.inference_model import InferenceCakeChatModel File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\inference_model.py", line 1, in <module> from cakechat.dialog_model.keras_model import KerasTFModelIsolator File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\keras_model.py", line 11, in <module> from cakechat.dialog_model.abstract_model import AbstractModel File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\abstract_model.py", line 6, in <module> from cakechat.dialog_model.quality.metrics.utils import MetricsSerializer File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\quality\__init__.py", line 2, in <module> from cakechat.dialog_model.quality.metrics.lexical_simlarity import calculate_lexical_similarity, get_tfidf_vectorizer File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\cakechat\dialog_model\quality\metrics\lexical_simlarity.py", line 3, in <module> from sklearn.feature_extraction.text import TfidfVectorizer File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\sklearn\__init__.py", line 64, in <module> from .base import clone File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\sklearn\base.py", line 13, in <module> from .utils.fixes import signature File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\sklearn\utils\__init__.py", line 16, in <module> from .fixes import _Sequence as Sequence File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\sklearn\utils\fixes.py", line 92, in <module> from scipy.sparse.linalg import lsqr as sparse_lsqr # noqa File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\scipy\sparse\linalg\__init__.py", line 114, in <module> from .isolve import * File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\scipy\sparse\linalg\isolve\__init__.py", line 6, in <module> from .iterative import * File "C:\Users\nisha\OneDrive\Desktop\cakechat-2.0.1\chatvirt\lib\site-packages\scipy\sparse\linalg\isolve\iterative.py", line 10, in <module> from . import _iterative ImportError: DLL load failed: The specified module could not be found. -
'Product' matching query does not exist
this is the views code, the item is in the database but it still brings DoesNotExist, i have also tried get_object_or_404 im trying this url http://127.0.0.1:8000/store/shirts/mavi-jeans/ def product_detail(request, category_slug, product_slug): try: single_product = Product.objects.get(category__slug=category_slug, slug=product_slug) except Exception as e: raise e context = {'single_product':single_product} return render(request, 'store/product_detail.html', context) urlpatterns = [ path('', views.store, name='store'), path('<slug:category_slug>/', views.store, name='products_by_category'), path('<slug:category_slug>/<slug:product_slug>/', views.product_detail, name='product_detail'), ] -
HTTP retrieval failure when creating drop-in audio chat using Twilio
I am leveraging the Twilio Programmable Voice API to create a drop in audio chat room when a user completes a signup form. I am using ngrok to listen to both my React frontend app and Django backend app so I can expose my local server to the internet. However, when I complete the form, I get the prompt to activate my mic and then hear the error Sorry, an application error has occurred, goodbye before my call drops. My Twilio error logs shows the error: Error - 11200 An attempt to retrieve content from https://f5b7-104-182-176-156.ngrok.io/voice_chat/rooms/Emmanuel returned the HTTP status code 404 HTTP retrieval failure Possible Causes Web server returned a 4xx or 5xx HTTP response to Twilio Misconfigured Web Server Network disruptions between Twilio and your web server No Content-Type header attached to response Content-Type doesn't match actual content, e.g. an MP3 file that is being served with Content-Type: audio/x-wav, instead of Content-Type: audio/mpeg When I do a GET on an endpoint that should show me all my rooms http://127.0.0.1:8000/voice_chat/rooms I get an empty list, indicating that no rooms have been created? Here is my React code: ... const NewRoom = () => { const [state, setState] = useGlobalState(); … -
Better solution to a increasing number game?
I am trying to build a game where on the server side I am providing a random number ex. 4.31. Then on the browser side users see a number growing from 1.00 to 4.31. They don't know the number provided from the server and have to just guess when to stop by clicking on a button. Right now I have a solution where I run everything as a background process using apscheduler. I run the function of increasing the number by 0.01 each 0.1 seconds and send the result to the front end using channels. I can't send the random number calculated in the background to front end as I think this is not safe. I am wondering if there is a better/more efficient solution to this as calling a function every 0.1s forever seems odd to me? I am happy to give more explanation/code examples if my question seems unclear. -
URL Variable Subdirectory Error in Django
A view in my Django app takes a URL variable/argument which in my case is a URL like: https://google.com so it would look something like this: localhost:8000/api/https://google.com Because the URL variable above contains slashes, Django will try to find new subdirectories whereas I want Django to ignore them. How can I achieve that??? -
Django - Form not saving when submitted
Good afternoon all, One of my form does not seem to save when submitted. I cannot see why, in particular as I have a similar form working just fine using the same code. For some reason it work just fine using the admin panel. My assumption is that I am missing something that tells the form it needs to be saved. But cannot find what. Any ideas? Models RATING=( (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5'), ) class ProductReview(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review_text=models.TextField(max_length=250) review_rating=models.IntegerField(choices=RATING,max_length=150, default=0) date_added = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) Views def add_review(request, product_id): product = Product.objects.get(pk=product_id) form = ReviewAdd(request.POST or None, instance=product) #instance=product (populate field with existing information) if form.is_valid(): form.save() return redirect('product') return render(request, 'main/add_review.html',{'form':form}) URL from django.urls import path from . import views urlpatterns = [ ... path('product/add_review/<product_id>', views.add_review,name="add_review"), ] Forms class ReviewAdd(forms.ModelForm): class Meta: model = ProductReview fields = ('review_text', 'review_rating') labels ={ 'review_text': '', 'review_rating': '', } widgets = { 'review_text': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Review'}), } Admin from django.contrib import admin from .models import Venue, User, Product, ProductReview from django.urls import path admin.site.register(User) admin.site.register(ProductReview) class ProductReview(admin.ModelAdmin): list_display=['user','product','review_text','get_review_rating'] HTML Page {% extends 'main/base.html' %} {% load crispy_forms_tags %} {% block title %} {% endblock %} {% block … -
ifcopenshell geom.settings OverflowError
im tying to serialize an ifc file to gltf using ifcopenshell: settings = ifcopenshell.geom.settings#(APPLY_DEFAULT_MATERIALS=True) sr_2 = ifcopenshell.geom.serializers.gltf(v_path.joinpath(glb_file_nom), settings) but I got this error: settings | Error in formatting: OverflowError: in method 'IteratorSettings_get', argument 2 of type 'uint64_t' when I run on blender I got this: Traceback (most recent call last): File "/snap/blender/2106/3.1/python/lib/python3.10/code.py", line 90, in runcode exec(code, self.locals) File "<blender_console>", line 1, in File "/home/fcr/.config/blender/3.1/scripts/addons/blenderbim/libs/site/packages/ifcopenshell/ifcopenshell_wrapper.py", line 857, in repr (", ".join(map(lambda x: "%s = %r" % (x, self.get(getattr(self, x))), d()))) File "/home/fcr/.config/blender/3.1/scripts/addons/blenderbim/libs/site/packages/ifcopenshell/ifcopenshell_wrapper.py", line 857, in (", ".join(map(lambda x: "%s = %r" % (x, self.get(getattr(self, x))), d()))) File "/home/fcr/.config/blender/3.1/scripts/addons/blenderbim/libs/site/packages/ifcopenshell/ifcopenshell_wrapper.py", line 220, in get return _ifcopenshell_wrapper.IteratorSettings_get(self, setting) OverflowError: in method 'IteratorSettings_get', argument 2 of type 'uint64_t' what am I missing? -
what is the use of creating a new way of url pattern in this code and what does it symbolize?
Blockquote file path of the url hello guys i am just a beginner in django so i cant understad what is the use of using this url pattern in this code from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.MEIDIA_URL, document_root=settings.MEDIA_ROOT) -
How would we set up LoginRequiredMixin? I am Getting following Error
Settings: LOGIN_URL = 'login_view' Views: class MyView(LoginRequiredMixin,View): template_name = "login.html" login_url = 'login.html' redirect_field_name = 'redirect_to' login_view = MyView.as_view() Url: urlpatterns = [ path('admin/', admin.site.urls), path('',include('blogApp.urls')), path("login_view/",view=MyView.as_view(template_name = "storefront/login.html"), name="login_view"), ] And Template is in ./templates/storefront/login.html I am getting Page not found (404) -
Django Framework : Problems with views settings
im learning Django framework and having some issues that i dont get it. Actually i have apps like Polls/ Blog/ and my homepage/ installed and working as i want. My problem is to display each data into my homepage_index.html like : _ how many Question my polls contain _ how many Article my blog contain Both of informations are from different apps. From Django Tutorial i found a solution to display by example my last 3 Question.objects like this. homepage/views.py : from django.views import generic from django.utils import timezone from polls.models import Question class homepage(generic.ListView): template_name = 'homepage/homepage_index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:3] my homepage_index.html working : {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a style="color: white; text-decoration: none;" href="{% url 'polls:detail.html' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} How can i define in my homepage/views.py with multiple context_object_name and multiple queryset please ? I tryied to read many documentations but im still failing -
REGISTER WITH ORM DJANGO [closed]
if I add in the database there is insertion in the customUser table and not in the customer table please help me it's urgent -
Django : Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Error When Click Button for send data. Please Helping me to solve problem. Error When Click Button for send data. Please Helping me to solve problem. Error When Click Button for send data. Please Helping me to solve problem. detail.html td> <!-- <a href="{% url 'Detail_pem' %}"><button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> </a> --> <button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> </td> </tr> {% endfor %} </tbody> </table> </div> <!-- <script type="text/JavaScript" src="{% static 'js/pem.js' %}"></script> --> <script> var id_order = document.getElementsByClassName('id_order') for (i = 0; i < id_order.length; i++) { id_order[i].addEventListener('click', function(){ var orid = this.dataset.product var ornm = this.dataset.act console.log('orid :', orid) console.log('ornm :', ornm) codata(orid, ornm) }) } function codata(orid, ornm){ console.log('orid :', orid, 'ornm :', ornm) const url = "Detail" fetch(url, { method :'POST', headers : { 'Content-Type' : 'application/json', 'X-CSRFToken' : csrftoken, }, body:JSON.stringify({'orid':orid, 'ornm':ornm}), }) .then((response) =>{ return response.json(); }) .then((data) => { console.log('Success:', data); }) } </script> {% endblock %} view.py def Detail(request): data = json.loads(request.body.decode("utf-8")) orid = data['orid'] ornm = data['ornm'] print('id :', orid,'nama :', ornm) context = {'orid ':orid , 'ornm':ornm} return render(request, 'store/detail.html', context ) -
Heroku Django Postgre
So, I was building a Django app, I created an intro field for a post formular, I did that in my models.py file: class Post(models.Model): title = models.CharField(max_length=100) intro = models.CharField(max_length=1024) content = models.TextField() pub_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('donut-post-detail', kwargs={'pk': self.pk}) I renamed 'description' into 'intro' so, when I did the makemigrations command it maked me a file named: 0002_rename_description_post_intro.py I hosted it into heroku, commited changes and migrated it when this happened: ~ $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions, sites, users Running migrations: Applying blog.0002_rename_description_post_intro...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "description" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 290, … -
Custom rest_framework_simplejwt authentication class for reading HTTPonly cookies ignores permission_classes = (permissions.AllowAny,)
I have defined a custom authentication class that extends the default rest_framework_simplejwt.authentication.JWTAuthentication as follows: myaccount.authenticate.py def authenticate(self, request): header = self.get_header(request) if header is None: # If header is None, get token from cookie raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_ACCESS_COOKIE']) or None else: raw_token = self.get_raw_token(header) if raw_token is None: return None validated_token = self.get_validated_token(raw_token) return self.get_user(validated_token), validated_token I then added the following to settings.py 'DEFAULT_PERMISSION_CLASSES':[ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_AUTHENTICATION_CLASSES':[ 'myaccount.authenticate.CustomJWTAuthentication' ] } views.py class Login(APIView): permission_classes = (permissions.AllowAny,) def post(self, request): pass When I make a call to the above view despite having permissions set to AllowAny, I get the following response. { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } What could I have missed? Thank you. -
Python list overwritten each time the previous items
The objective of my application is to create a copy of documents and insert them into the database for each annotator, for example, let's say the master user has 3 documents and two annotators, let's say the first annotator has the email testmail1@mail.com and the second one has the email testmail2@mail.com, finally, I need to insert in the database 3 documents for testmail1@mail.com and 3 other documents for testmail2@mail.com. So to do this, I created first a list containing the copy of documents, and I didn’t assign the annotator created_documents_in_iaa = [] created_documents_in_iaa += [DocumentIAATask( name=document.name, spans=document.spans, entity=document.entity, original_document=document, IAA_Task=iaa_task) for document in all_documents_in_iaa.iterator(chunk_size=1)] And after that, I added an annotator to each document, and I append each modified created_documents_in_iaa list to the tsks_list: tasks_list = [] for user in users_instance_list: try: for i in range(len(created_documents_in_iaa)): created_documents_in_iaa[i].annotator = user tasks_list.append(created_documents_in_iaa) except Exception as e: print(e) Finally, I created a copy of documents in the PostgreSQL database: for task in tasks_list: DocumentIAATask.objects.bulk_create(task) However, in the result, I found 6 documents inside the table of the first annotator, and nothing for the other one, after I debugged the code, I found that tasks_list overwritten each time the list, that's means when I … -
Best approach to implement server-side caching on a Django GraphQL API?
I have an Angular frontend that uses Apollo Graphql client to interface with a Django Graphql backend (using graphene). It all works well, but the API is very slow, especially when there are concurrent users. I am trying a few things to speed up the API server. One of the things that I am seriously considering is to use server-side caching. I'm aware that there are some caching solutions that exist for Django out of the box, but these seem to be for caching the views. Is it possible to use these methods to cache Graphql API requests? What is the most effective caching solution for caching the responses to graphql queries in Django? I'm posting some of my project's code here so that you get a sense of how my API works. This is a sample of the Query class containing the various graphql endpints that serve data when queries are received from the client. And I suspect this is where we'll need most of the optimization and caching applied:- class Query(ObjectType): # Public Queries user_by_username = graphene.Field(PublicUserType, username=graphene.String()) public_users = graphene.Field( PublicUsers, searchField=graphene.String(), membership_status_not=graphene.List(graphene.String), membership_status_is=graphene.List(graphene.String), roles=graphene.List(graphene.String), limit=graphene.Int(), offset=graphene.Int()) public_institution = graphene.Field(PublicInstitutionType, code=graphene.String()) public_institutions = graphene.Field(PublicInstitutions, searchField=graphene.String(), limit = … -
I can't run websocket django in server nginx
nginx map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name www.abo3aly.com abo3aly.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/www/abo3aly.com; } location / { include proxy_params; proxy_pass http://unix:/run/abo3aly.sock; } location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass http://127.0.0.1:8002; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } *The error* _____ ERROR [Failure instance: Traceback: <class 'TypeError'>: __call__() got an unexpected keyword argument 'scope' /root/django/nayf/env/lib/python3.8/site-packages/autobahn/websocket/protocol.py:2878:processHandshake /root/django/nayf/env/lib/python3.8/site-packages/txaio/tx.py:369:as_future /root/django/nayf/env/lib/python3.8/site-packages/twisted/internet/defer.py:190:maybeDeferred /root/django/nayf/env/lib/python3.8/site-packages/daphne/ws_protocol.py:72:onConnect --- --- /root/django/nayf/env/lib/python3.8/site-packages/twisted/internet/defer.py:190:maybeDeferred /root/django/nayf/env/lib/python3.8/site-packages/daphne/server.py:200:create_application] -
Django Github CI cannot connect to mysql 'db'
Issue When trying to setup a Github action to test a Django project automatically, we ran into an issue with the django.yml setup. Whenever we ran the .yml, we got this exception on the last step (python manage.py test): django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (-3)") To state, our docker environment and tests alone work fine, just when trying to do this in a Github action, we get issues. What we have tried We have tried running a docker-compose up -d before running the test, to know for sure that our DB is running. Tried adding environment variables with DB info like this: https://github.com/Cuda-Chen/django-mysql-github-actions-demo/blob/main/.github/workflows/django-ci.yml Current code name: Django CI on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.8] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests run: | python manage.py test Does anyone know what is going on here, and how we can resolve this? -
When I gave command on CMD manage.py runserver it instead took me into VS Code and when i ran it in VS code error was on (from django.core.management)
when I ran the command on CMD manage.py runserver it intern redirected to VS Code. When I tried to run on VS Code it showed the system cannot find the specified path. It was underlining this statemnt try: from django.core.management ---------------------- -
Django: The QuerySet value for an exact lookup must be limited to one result using slicing
i am tring to access a page using a slug url, but i keep getting this error The QuerySet value for an exact lookup must be limited to one result using slicing. i thought it would be a filter or get error in my view but i don't know where the error is coming from view.py def tutorial_topic_category(request, slug): tutorial_category = TutorialCategory.objects.get(slug=slug) tutorial_topic_category = TutorialTopicCategory.objects.filter(tutorial_category=tutorial_category) context = { 'tutorial_topic_category': tutorial_topic_category, } return render(request, 'tutorials/tutorial_topic_category.html', context) def topic(request, slug, slug2): tutorial_category = TutorialCategory.objects.get(slug=slug) tutorial_topic_category = TutorialTopicCategory.objects.filter(tutorial_category=tutorial_category) topic = Topic.objects.get(slug=slug2, tutorial_topic_category=tutorial_topic_category) context = { 'topic': topic, } return render(request, 'tutorials/topic.html', context) urls.py path("<slug>", views.tutorial_topic_category, name='tutorial-topic-category'), path("<slug>/<slug2>", views.topic, name='topic') and how do i pass in the slug in my template using django template tag <a href="{% url 'tutorials:topic' category.slug category.slug2 %}"> -
Celery task is pending in the browser but succeeded in the python shell of Django
I'm using Django, Celery, and RabbitMQ for simple tasks on Ubuntu but celery gives no response. I can't figure out why the task is pending in the browser, while it is done when I used the shell by executing python3 manage.py shell. Here is my tasks.py file: from celery import shared_task, task @shared_task def createContainer(container_data): print(container_data,"create") return "created" @shared_task def destroyContainer(container_data): print(container_data,"destroy") return "destroyed" Here is my views.py file: def post(self,request): if str(request.data["process"]) == "create": postdata = { "image_name" : request.data["image_name"], "image_tag" : request.data["image_tag"], "owner" : request.user.id } # I tried to print the postdata variable before the task and it is working createContainer.delay(postdata) elif str(request.data["process"]) == "destroy": postdata = { "cont_id" : request.data["cont_id"] } # I tried to print the postdata variable before the task and it is working destroyContainer.delay(postdata) # I tried to print anything here, but it was not reachable and never executed Here is the code I tried in the shell: >>> from dockerapp.tasks import create_container >>> create_container.delay("fake data") >>> <AsyncResult: c37c47f3-6965-4f2e-afcd-01de60f82565> Also, I can see the logs of celery here in another terminal by executing celery -A dockerproj worker -l info It results in these lines when I used the shell: Received task: dockerapp.tasks.create_container[c37c47f3-6965-4f2e-afcd-01de60f82565] fake … -
When i create Django Project with environment i have had a mistake line but when i deleted the environment file the line had disappeared !! Any Idea?
import os from django.core.wsgi import get_wsgi_application // Mistake in any import commands line but it is working os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AIDjango.settings') application = get_wsgi_application()