Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting a 404 error while testing a django listview?
I have a ListView of movies. For viewing this list the user has to be authenticated. I create a user in the testing runtime with self.user = User.objects.create_user(username='fake_user', email='user@fakeemail.com', first_name='fake', last_name='user') self.user.set_password('password') self.user.save() and then when I run this test self.client.login(username='fake_user', password='password') response = self.client.get(reverse('movie-list')) self.assertEqual(response.status_code, 200) I always get a 404 response, even though I have no problem when accessing this URL from the browser. What am I missing here? -
how can I use LoginView in my own view and show in HTML templates?
I want to use ready Django LoginView, but in the same time I have to use my own view for registration in same HTML template. If in urls.py file I will connect 2 views than i will connect only first. So my question is that how can use LoginView in my own view and use 2 forms with jinja? here is my views.py file and html ;) def index(request): if request.method == 'POST': form = UserRegisterForm(request.POST) formlog = auth_views.LoginView.as_view(template_name='main/index.html') if 'signup' in request.POST: if form.is_valid(): form.supervalid() form.save() username = form.cleaned_data.get('username') messages.success(request, f'Dear {username} you have been created a new accound!') return redirect('main') elif 'login' in request.POST: if formlog.is_valid(): formlog.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('main') else: form = UserRegisterForm() formlog = auth_views.LoginView.as_view(template_name='main/index.html') return render(request, 'main/index.html', {'form': form, 'formlog': formlog}) # this code is not working , but not returning any errors HTML {% if not user.is_authenticated %} <!-- Login --> <div class="container"> <div class="log-1"> <div class="log-0"> <p class="logtitle">BareTalk</p> <form method="POST" name="login"> {% csrf_token %} {{ formlog|crispy }} <button class="log-button first" type="submit">Login</button> </form> <button class="log-button second" onclick="modalwindowops.open();" id="signup">Sign Up</button> </div> </div> </div> <!-- Signup --> <div class="modal-overlay"> <div class="modal-window"> … -
Users can't pay each other django-paypal
I have an online store where users can pay each other to buy things, I have been testing it with sandbox accounts but I don't think it's working. I really can't get where the issue is Here is my views.py: def payment_process(request, trade_id): trade = get_object_or_404(Trade, id=trade_id) host = request.get_host() paypal_dict = { 'business': trade.seller.email, 'amount': Decimal(trade.price), 'item_name': trade.filename, 'invoice': str(trade.id), 'currency_code': 'USD', 'notify_url': 'https://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'https://{}{}/{}'.format(host, *reverse('payment_done', kwargs={'trade_id': trade.id})), 'cancel_return': 'https://{}{}'.format(host, reverse('home')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'payment/payment_process.html', {'trade': trade, 'form': form}) @csrf_exempt def payment_done(request, trade_id): # Do some very important stuff after paying ... # It would be really nice if someone can help me with a checker messages.success(request, 'Your product is in your inbox now') return redirect('trade:inbox') My urls.py: urlpatterns = [ path('admin/', admin.site.urls), ... # Prodbox Payment path('payment/process/<int:trade_id>/', payment_views.payment_process, name="payment_process"), path('payment/done/<int:trade_id>/', payment_views.payment_done, name="payment_done"), # Prodbox packages path('paypal/', include('paypal.standard.ipn.urls')), ] The template which handles paying: {% extends 'users/base.html' %} {% block title %}Payment Process | Prodbox {% endblock title %} {% block content %} <div class="container row justify-content-center"> <div class="shadow-lg p-3 mb-5 col-md-8 bg-white rounded m-4 p-4"> <section> <p>Seller: {{ trade.seller.email }}</p> <p>Product: {{ trade.thing }}</p> <p style="color: #2ecc71;">Price: ${{ trade.price }}</p> </section> <section> <h4>Pay … -
In Python 3.7 ,Django3.1.1 ,Apache/2.4.46 (cPanel) getting ther error : AttributeError: 'module' object has no attribute 'lru_cache'
I am new to deploying the Django project on cpanel. My cpanel was on python 2.7 but my project need python3.7 so I have installed a separate version of python 3.7 on cpanel by following this tutorial https://sysally.com/blog/install-python-3-x-whm-cpanel-server/ .After successfully installing python 3.7 I followed this tutorial to server my project on cpanel https://docs.cpanel.net/knowledge-base/web-services/how-to-install-a-python-wsgi-application/ Firstly I was getting this error "ImportError: No module named django.core.wsgi" which i have solved by adding my virtual environment path to wsgi.py file , now my project wsgi.py file looks like this import os, sys # add the virtualenv site-packages path to the sys.path sys.path.append('/home/***/public_html/app/unltdenv/lib/python3.7/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'unltdsample.settings') application = get_wsgi_application() Now I am getting this error Traceback (most recent call last): File "/opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 369, in <module> app_module = load_app() File "/opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts/wsgi-loader.py", line 76, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/home/umadmin/public_html/app/unltd/passenger_wsgi.py", line 1, in <module> from unltdsample.wsgi import application File "/home/umadmin/public_html/app/unltd/unltdsample/wsgi.py", line 19, in <module> from django.core.wsgi import get_wsgi_application File "/home/umadmin/public_html/app/unltdenv/lib/python3.7/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/umadmin/public_html/app/unltdenv/lib/python3.7/site-packages/django/utils/version.py", line 71, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' i have searched about it, what i found is that the problem is of wsgi python version mismatch. … -
Django get correct userprofile for user.id
I am using DRF to create an api where to get userprofile according to the user.id from url like path('<id>/profile', UserProfileView.as_view(), name='profile') The view Looks like class UserProfileView(RetrieveAPIView): queryset = models.Profile.objects.order_by("-id") serializer_class = serializers.UserProfileSerializer lookup_field = 'id' permission_classes = (permissions.AllowAny, ) #serializers.py class UserProfileSerializer(serializers.ModelSerializer): name = serializers.CharField(source='user.name', read_only=True) email = serializers.CharField(source='user.email', read_only=True) class Meta: model = models.Profile fields = '__all__' extra_kwargs = {'password': {'write_only': True}} lookup_field = 'id' def create(self, validated_data): user = models.Profile( email=validated_data['email'], name=validated_data['name'] ) user.set_password(validated_data['password']) user.save() return user #models.py class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bio = models.TextField(default='', max_length=800, blank=True) The api return an userprofile object as { id: 4, name: "kehoji", email: "kehoji2061@vmgmails.com", bio: "", user: 3} But for same logged in user returns { name: "kehoji", id: 3, email: "kehoji2061@vmgmails.com" } so, when I try to fetch userprofile by user.id it return other profile. How I can I solve this. This mismatch happend because I deleted the user of id=2. -
. Package install error: Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE] Error launching application on MSEmulator. Exited
Launching lib\main.dart on MSEmulator in debug mode... ✓ Built build\app\outputs\flutter-apk\app-debug.apk. Installing build\app\outputs\flutter-apk\app.apk.. -
How do I create a new user model in Django named student without modifying the already existing base user?
So in my academic management system when I want to modify the model student with fields like class and division but the base admin used that I create with create super user should remain the same . How to achieve this in Django ? -
Index out of range & name 'messages' is not defined
I am trying to import .csv file to database and getting index out of range.(List range) My file fields are as shown below. I have tried by changing delimiter value but no luck.My view.py file is views.py def contact_upload(request): prompt = { 'order': 'Order of the CSV file should be releasedate,moviename,hero,heroine,rating' } if request.method == "GET": return render(request, 'testapp/upload.html') csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, "This is not a CSV file") data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=' ', quotechar="|"): # print(column) _, created = Movie.objects.update_or_create( releasedate=column[0], moviename=column[1], hero=column[2], heroine=column[3], rating=column[4] ) context = {} return render(request, 'testapp/upload.html', context) upload.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {%if messages %} {% for message in messages %} <div> <strong>{{message|safe}}</strong> </div> {% endfor %} {% else %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Upload a File:</label> <input type="file" name="file"> <p>Only accept CSV File.</p> <button type="submit">Upload</button> </form> {% endif %} </body> </html> Problem2: #I am using ImportExportModelAdmin for importing and exporting data but here id value is get added by django and based on this only changes are happening.I want to change id field and wanted to make hero field to be considered for … -
winapi.WaitForSingleObject takes a long time to execute while django is performing system checks
I'm running Django 3.0.8 and windows 10. I've got a development server running on my local machine that usually "performs system checks" then starts up nice and promptly ( after a few seconds). At this time the winapi.WaitForSingleObject process takes in the order of 1000ms to execute. At times winapi.WaitForSingleObject will take up to 60,000ms (!!) to execute (I think it's timing out, but I'm not sure). I can't find any pattern to these slow starts. I don't know what the 'SingleObject' is that's causing the delay. What steps can I take to prevent winapi.WaitForSingleObject from taking so long to execute? -
Views in the Django model
I'm a beginner in Django and I need your help. Please tell me how I can make it so that when you go to the page with the article, in my model views = models.IntegerField(default=0, verbose_name='Views') were views read and added to the database? models.py class News(models.Model): title = models.CharField(max_length=150, verbose_name='Наименование') content = models.TextField(blank=True, verbose_name='Контент') created_ad = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации') updated_at = models.DateTimeField(auto_now=True, verbose_name='Обновлено') photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Картинка', blank=True) is_published = models.BooleanField(default=True, verbose_name='Опубликовано') category = models.ForeignKey('Category', verbose_name='Категория', on_delete=models.PROTECT) # on_delete=models.PROTECT - защита от удаления статей привязанных к категории. views = models.IntegerField(default=0, verbose_name='Просмотры') def get_absolute_url(self): return reverse('view_news', kwargs={"pk": self.pk}) # Строковое представление объекта def __str__(self): return self.title -
Supporting multiple requests - django API backend
I'm currently building a backend API for a chat app with Django and DRF. It basically handles direct interaction with a MySQL database and also manages other important components like authentication, authorization, and user management. Our team has built an API microservice for enabling chat on our client mobile app. We're doing this through websockets and rabbitMQ on node.js. So we've put this up online and are realizing that the Django backend doesn't seem to support the vast requests being sent from the chat API. Running a load test on the Django app shows that it's dropping up to 90% or requests. Adding more servers connected to a load balancer has not improved the situation either. I suppose this is being bottlenecked by the blocking nature of Django (actually DRF in particular). But it's just my hunch and I'm not really sure as to what the problem really is. Does anyone have advice on how to improve performance for the Django API. -
Django FileField/ImageField validation when the file upload is being done from the client side
When ever client wants to upload a file it first request the Django server for a pre-signed URL the server then generates a pre-signed URL and sends it back to the client. The client can use this URL to upload to file directly to S3. Once the upload is successful the client sends the file key back to the server (the file key is also present in the response given by the server along with the URL). Now I'm confused as to how to pass the FileField validation given that I only have the file key with me and not the actual file. For example: class Company(models.Model): name = models.CharField(max_length=100) logo = models.ImageField(null=True) def __str__(self): return f'name:{self.name}' class CompanySerializer(serializers.ModelSerializer): CLIENT_COMPANY_LOGO_KEY = 'logo' def to_internal_value(self, data): # Replace file/image keys with file/image instances so that they can pass validation. if data.get(self.CLIENT_COMPANY_LOGO_KEY): try: data[self.CLIENT_COMPANY_LOGO_KEY] = default_storage.open(data[self.CLIENT_COMPANY_LOGO_KEY]) except (TypeError, OSError, ParamValidationError): pass return super().to_internal_value(data) def process_logo(self, validated_data): logo = validated_data.get(self.CLIENT_COMPANY_LOGO_KEY) if logo: # Replace file/image instances with keys. validated_data[self.CLIENT_COMPANY_LOGO_KEY] = logo.name return validated_data def create(self, validated_data): validated_data = self.process_logo(validated_data) company = super().create(validated_data) return company Within the serializer I'm first replacing the file key with the actual file using the default_storage which is hooked … -
Django REST serializer, how to add extra field and set it
I need your help, extending classes is beyond my current Python skills. Django 3.1 and Django-Rest-Framework. I would like to add "detail_url" field to VideoSerializer, and set its value based on existing field on model. "detail_url" is not defined in model, I would like to generate it on the fly when view is called. I figure, serializer is the best place to do it. Thank you serializers.py from rest_framework import serializers from django.urls import reverse from main.models import Video class VideoSerializer(serializers.ModelSerializer): detail_url = serializers.URLField() class Meta: model = Video fields = ['uuid', 'url', 'title', 'thumbnail_url', 'detail_url'] # fields = '__all__' detail_url = reverse('video_detail', model.uuid) # <- this is the part I dont know where to declare views.py def dashboard(request): context = {} if request.method == 'GET': user = request.user # retrieve user's videos videos = Video.objects.filter(user=user) if videos.exists(): serializer = VideoSerializer(videos, many=True) context['videos'] = json.dumps(serializer.data) return render(request, 'main/dashboard.html', context) -
do backend frameworks will exist?
Do firebase or aws ends the necessity of a backend framework like django? I am keen to learn django but I'm confused that after some years there could be no need for any backend framework. Is that so? -
Many to one relationship in Django template
I have a one to many relationship and I want to render it to my template class DataType(models.Model): name = models.CharField(max_length=100, blank=True) code = models.CharField(max_length=5) def __str__(self): return self.name class AgroDataType(models.Model): name = models.CharField(max_length=100, blank=True) code = models.CharField(max_length=5) dataType = models.ForeignKey(DataType, on_delete=models.CASCADE) def __str__(self): return self.name I tried to use it like this. but it doesn't work. {% for data in agro_data_types %} <h1>{{data.name}}</h1> {% for datas in data.dataType %} <h1>{{datas.name}}</h1> {% endfor %} {% endfor %} -
How to resolve “Error during WebSocket handshake: Unexpected response code: 503” error in a Django Channels Heroku app?
The error in the console : app.e05f6d1a6569.js:105 WebSocket connection to 'wss://domecode.com/wss?session_key=${sessionKey}' failed: Error during WebSocket handshake: Unexpected response code: 503 (anonymous) @ app.e05f6d1a6569.js:105 mightThrow @ jquery.js:3762 process @ jquery.js:3830 I'm running a Django Channels app ( Messaging app ) on Heroku using Daphne. All the files that correspond to this problem are included in this question. routing.py - messaging app from messaging import consumers from django.urls import re_path websocket_urlpatterns = [ re_path(r'^ws$', consumers.ChatConsumer), ] app.js - snipped of the websocket part of the app.js file var ws_scheme = window.location.protocol == 'https:' ? 'wss' : 'ws'; var socket = new WebSocket(ws_scheme + '://' + window.location.host + '/' + ws_scheme + '?session_key=${sessionKey}'); asgi.py - project's asgi import os import django # from django.core.asgi import get_asgi_application from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'domecode.settings') django.setup() # to deploy with asgi when using channels application = get_default_application() Procfile release: python3 manage.py makemigrations && python3 manage.py migrate web: daphne domecode.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python3 manage.py runworker channel_layer -v2 Any information on what went wrong here? Sidenote: It works perfectly fine in the development server however it gives the error mentioned at the top in the production server at https://domecode.com/chat/. When I send a message … -
How to store a list of values inside a variable and trigger them dynamically in Django?
Hello: complete newbie here. I'd like to store a list of values inside a variable (in a DB) in such a manner: Variable = $FavoriteShoes Values = fave shoes, favorite kicks, lucky shoes Variable = $BrandOfShoes Values = nike, vans, aldo's I'd like to make it so that when $FavoriteShoes is found on a page, any one of the values (randomly) is triggered. So, I could have on a template: My $FavoriteShoes are $BrandOfShoes. And it would be executed as: My fave kicks are vans. How would this be possible in Django? -
Python Django - how to show model changes on a page without refreshing it using Ajax? HELP ME PLEASE)
Python Django. I have a model: class text(models.Model): text = models.TextField('Текст' ,blank = False) time = models.CharField('Время',max_length = 200,blank = False) And I output them all in html: {% for object in text %} <div class="row"> <div class="col-xl-3 block_messeage"> <span class="span_block_messeage"> ,{{object.time}}</span> <br> {{object.text}} </div> </div> {% endfor %} everything is displayed successfully, but the class text is increasing every second and I need to show these changes without refreshing the page. Tell me how this can be implemented using ajax, I will be very grateful) -
How to resolve "Error during WebSocket handshake: Unexpected response code: 503" error in Django Channels app on Heroku?
Error in the console : app.e05f6d1a6569.js:105 WebSocket connection to 'wss://domecode.com/wss?session_key=${sessionKey}' failed: Error during WebSocket handshake: Unexpected response code: 503 (anonymous) @ app.e05f6d1a6569.js:105 mightThrow @ jquery.js:3762 process @ jquery.js:3830 I'm running a Django Channels app ( Messaging app ) on Heroku using Daphne. All the files that correspond to this problem are included in this question. routing.py - messaging app from messaging import consumers from django.urls import re_path websocket_urlpatterns = [ re_path(r'^ws$', consumers.ChatConsumer), ] app.js - snipped of the websocket part of the app.js file var ws_scheme = window.location.protocol == 'https:' ? 'wss' : 'ws'; var socket = new WebSocket(ws_scheme + '://' + window.location.host + '/' + ws_scheme + '?session_key=${sessionKey}'); asgi.py - project's asgi import os import django # from django.core.asgi import get_asgi_application from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'domecode.settings') django.setup() # to deploy with asgi when using channels application = get_default_application() Procfile release: python3 manage.py makemigrations && python3 manage.py migrate web: daphne domecode.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python3 manage.py runworker channel_layer -v2 Any clue what went wrong? Extra information: It works perfectly fine in the development server however it gives the error mentioned at the top in the production server at https://domecode.com/chat/. When I send a message on the … -
django-import-export append column to imported .xlsx
i want to append a column to the imported excel table, this column will contain the foreignKey to a model (the same in all rows, this foreignKey is obtained from the same form as the .xlsx), but i can't make it work. If i upload the excel with the column and the id it works perfectly. This is my code: views.py def article_import(request): if request.method == 'POST': provider_id = request.POST['provider_id'] article_resource = ArticleResource() dataset = Dataset() nuevos_articulos = request.FILES['xlsfile'] data_to_import = dataset.load(nuevos_articulos.read()) result = article_resource.import_data(dataset, dry_run=True, provider_id=provider_id) #Test data if not result.has_errors(): article_resource.import_data(dataset, dry_run=False, provider_id=provider_id) #Import data return redirect('dash-articles') return redirect('/dashboard/articles/?error=True') else: providers = Provider.objects.all().order_by('razon_social') return render(request, 'import/articles_import.html', {'providers': providers}) resource.py class ArticleResource(resources.ModelResource): class Meta: model = Article skip_unchanged = True report_skipped = False import_id_fields = ('codigo',) def before_import(self, dataset, using_transactions, dry_run, **kwargs): dataset.append_col([kwargs['provider_id'],], header='proveedor') print(dataset) return super().before_import(dataset, using_transactions, dry_run, **kwargs) The code in "before_import" is what i was testing but i can't make work the "append_col" function. I will apreciate the help, and if there is a better solution please tell me, thanks!!! -
How to send a 2 Django view context objects to single html template in Django?
Please help me, I'm working on a project where I need to display a page about tutors and need to add their ratings also.so I created 2 models and 2 views for both tutors but I don't know how to display the context objects of both views in a single template. class tutors(models.Model): category = models.ForeignKey(Category, related_name='tutors', on_delete=models.CASCADE) name = models.CharField(max_length=100, db_index=True) Tagline = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) description_tutor = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) images=models.ImageField(upload_to="media") qualification=models.TextField(null=True) class Meta: ordering = ('name', ) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('onlinetutors:tutor_detail', args=[self.id, self.slug]) class ratings(models.Model): username= models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,) rating=models.FloatField() tutorname=models.ForeignKey(tutors,related_name='ratingss',on_delete=models.CASCADE) created_date=models.DateTimeField(auto_created=True) def tutor_detail(request, id, slug): tutor = get_object_or_404(tutors, id=id, slug=slug) context = { 'tutor': tutor, } return render(request, 'detail.html', context) def rating(request,tutorname_id): display_rating = ratings.objects.filter(tutorname_id=tutorname_id).aggregate(find_average=Avg('rating')) display = display_rating["find_average"] return render(request, 'detail.html',{'display':display}) -
How to display two models as one in Django?
I have two models - Image and Article, that are not related to each other in any other way than both having the creation date field. I want to treat them as though they "were one" - I need to display them both in one div. class Image(models.Model): image = models.ImageField(upload_to="slider/") created = models.DateTimeField(auto_now_add=True) class Article(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) body = models.TextField() created = models.DateTimeField(auto_now_add=True) Having this, I want to be able to render them both in one div so they all go by the creation day, regardless of their class; I want them to be mixed up. -
All django project failed after upgrading to Ubuntu 20.04
I upgraded my system from Ubuntu 18.04 to 20.04.1 LTS, and ALL my Django projects crashed. One of the errors related to psycopg2 in the virtual environment. But this is solvable by not specifying the version in requirements.txt. However, there are different errors for different projects even if I rebuilt the virtual environment one by one. I think it might be due to the fact that those packages do not support python 3.8 yet. So, how to I get my Django project running in Ubuntu 20.04? -
How to make django celery use the redis broker url?
(venv) [riyad@Fury django_celery]$ celery -A django_celery worker -l info <Celery django_celery at 0x7f0917d57fa0> -------------- celery@Fury v4.3.0 (rhubarb) ---- **** ----- --- * *** * -- Linux-5.8.6-1-MANJARO-x86_64-with-glibc2.2.5 2020-09-30 02:54:36 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: django_celery:0x7f0917d57fa0 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . django_celery.celery.debug_task . example.task.sleepy [2020-09-30 02:54:36,989: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 2.00 seconds... [2020-09-30 02:54:38,996: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 4.00 seconds.. the main issue cause by this redis broker url, so far i am running a redis server on my other terminal. i am using two libraries redis and celery my settings.py file-> CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } BROKER_TRANSPORT = "redis" BROKER_HOST = "localhost" # Maps to redis host. BROKER_PORT = 6379 # Maps to redis port. BROKER_VHOST = "1" # Maps … -
Get Display CHOICE in a ForeignKey Django Model
My models: class Sell(models.Model): item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE) date = models.DateField(default=timezone.now) code = models.ForeignKey(Order, related_name='order', on_delete=models.CASCADE, null=True, blank=True) class Order(models.Model): status_choice = ( ("W", "Aguardando aprovação do pagamento"), ("A", "Pagamento aprovado - produto em separação"), ) code = models.CharField(max_length=100) status = models.CharField(max_length=1, choices=status_choice, default='W') My template: {% for order in orders %} <tr> <td>{{ order.code__code }}</td> <td>{{ order.date }}</td> <td>{{ order.get_code__status_display }}</td> </tr> {% endfor %} The output I was expecting: "Aguardando aprovação do pagamento" but it's not printing this. Any help to display the full text instead the only word "W"? Thank you!