Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF foreignkey serializer - how to return only the latest object?
I currently have to models where a Node can have many Benchmark's, but when displaying it to the end users, I only want the serializer to return the latest benchmark for the node, instead of all of them which it currently does. How can I do this? Models.py class Node(models.Model): node_id = models.CharField(max_length=42, unique=True) wallet = models.CharField(max_length=42, null=True, blank=True) earnings_total = models.FloatField(null=True, blank=True) data = models.JSONField(null=True) online = models.BooleanField(default=False) version = models.CharField(max_length=5) updated_at = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Benchmark(models.Model): benchmark_score = models.IntegerField() benchmarked_at = models.DateTimeField(default=timezone.now) provider = models.ForeignKey(Node, on_delete=models.CASCADE) serializers.py class BenchmarkSerializer(serializers.ModelSerializer): class Meta: model = Benchmark fields = ['benchmark_score', 'benchmarked_at'] class NodeSerializer(serializers.ModelSerializer): benchmark_set = BenchmarkSerializer(many=True) class Meta: model = Node fields = ['earnings_total', 'node_id', 'data', 'online', 'version', 'updated_at', 'created_at', 'benchmark_set'] -
why at django framework vscode extension pylance giving me reed line at path
please click here for resolving error please someone resolve this problem why vs code giving me red line on path on django framework -
is it safe to compare owner_id to request.user.id for authentication in django?
in my app I have the model: class Meal(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=500) carbohydrates = models.FloatField() protein = models.FloatField() fat = models.FloatField() fiber = models.FloatField() owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) the following serializer: class MealSerializer(serializers.ModelSerializer): class Meta: model = Meal fields = "__all__" and this viewset: class MealViewSet(viewsets.ModelViewSet): queryset = Meal.objects.all() serializer_class = MealSerializer def get_queryset(self): return Meal.objects.filter(owner_id=self.request.user.id) And now I have a question, is it safe to compare owner_id=self.request.user.id in get_queryset method for authentication? or is it possible somehow to specify user.id in request e.g. using postman and pull all Meal objects? for example: Is that possible in postman or somewhere else? I am a beginner in django and rarely used postman. Sorry if I wrote something wrong, English is not my native language. -
How to change browse button to look like modern drag&drop?
I have created a django site, django site is working in this way. You go to the site, upload document with data and you get some results. You upload excel file, and you download excel file. In background I used pandas for calculations. In the end you can see code. I have left one thing to finish. I want to create drag&drop for upload document. Chech picture 1, as I understand this is already drag&drop, just doesn't look as I would like to. I want to look like in picture 2. Picture 1: Current Picture 2: I would like to look like this. Can I change the look that you seen on first image without using js? This is html that I have and output is shown in picture 1... {% extends "base.html" %} {% load static %} {% block content %} <form action="{% url "cal" %}" method="post" enctype="multipart/form-data" class="dropzone"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload and Download!"/></p> </form> {% endblock content %} This is function in views def OnlyCAL(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): … -
ERROR: Failed building wheel for PyNaCl trying to install pymssql on M1 silicon with Monterey OS with pip install
Tried installing pymssql on an M1 device with Monterey 12.0 on pycharm using pip install and failed with the below error tried installing freetds, force linking it, and installing OpenSSL nothing helped. Versions: Python - 3.8.9 Pip-21.3.1 freetds- 1.3.3 mysql-connector>=2.2.9 tried both pymssql<3.0 && pymssql==2.2.2 tried both Cython==0.29.24 && Cython>=0.29.24 Building wheel for PyNaCl (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users//code//venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/23/h968y6f510l5r_pngp0d5bzm0000gq/T/pip-install-3t__09es/pynacl_f3395a623f074763b680641bfc68bebd/setup.py'"'"'; file='"'"'/private/var/folders/23/h968y6f510l5r_pngp0d5bzm0000gq/T/pip-install-3t__09es/pynacl_f3395a623f074763b680641bfc68bebd/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/23/h968y6f510l5r_pngp0d5bzm0000gq/T/pip-wheel-ys2kjl3_ cwd: /private/var/folders/23/h968y6f510l5r_pngp0d5bzm0000gq/T/pip-install-3t__09es/pynacl_f3395a623f074763b680641bfc68bebd/ Complete output (29 lines): /Users//code//venv/lib/python3.8/site-packages/setuptools/installer.py:27: SetuptoolsDeprecationWarning: setuptools.installer is deprecated. Requirements should be satisfied by a PEP 517 installer. warnings.warn( Traceback (most recent call last): File "", line 1, in File "/private/var/folders/23/h968y6f510l5r_pngp0d5bzm0000gq/T/pip-install-3t__09es/pynacl_f3395a623f074763b680641bfc68bebd/setup.py", line 203, in setup( File "/Users//code//venv/lib/python3.8/site-packages/setuptools/init.py", line 152, in setup _install_setup_requires(attrs) File "/Users//code//venv/lib/python3.8/site-packages/setuptools/init.py", line 147, in _install_setup_requires dist.fetch_build_eggs(dist.setup_requires) File "/Users//code//venv/lib/python3.8/site-packages/setuptools/dist.py", line 806, in fetch_build_eggs resolved_dists = pkg_resources.working_set.resolve( File "/Users//code//venv/lib/python3.8/site-packages/pkg_resources/init.py", line 771, in resolve dist = best[req.key] = env.best_match( File "/Users//code//venv/lib/python3.8/site-packages/pkg_resources/init.py", line 1056, in best_match return self.obtain(req, installer) File "/Users//code//venv/lib/python3.8/site-packages/pkg_resources/init.py", line 1068, in obtain return installer(requirement) File "/Users//code//venv/lib/python3.8/site-packages/setuptools/dist.py", line 877, in fetch_build_egg return fetch_build_egg(self, req) File "/Users//code//venv/lib/python3.8/site-packages/setuptools/installer.py", line 87, … -
How to resolve user into the field?
I'm creating a simple To Do app using Django 3.2, and I have stuck in a error which is: FieldError: Cannot resolve keyword 'user' into field. Choices are: content, created, email, id, name, user1, user1_id This is models.py: from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields import CharField from django.contrib.auth.models import User # Create your models here. class User(models.Model): content = models.CharField(max_length=200, null=True) created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) user1 = models.ForeignKey(User, on_delete=CASCADE) def __str__(self): return self.content forms.py from django import forms from django.forms import ModelForm, fields from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] views.py from django.shortcuts import render, redirect from django.http.response import HttpResponse from django.utils import timezone from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from demo.forms import CreateUserForm from .models import * from .models import __str__ # Create your views here. @login_required(login_url='/login') def home(request): user = request.user all_items = User.objects.filter(user=user).order_by("created") context = {'all_items': all_items} return render(request, 'html/home.html', context) @login_required(login_url='/login') def add_content(request): current_date = timezone.now() newItem = User(content=request.POST.get('content')) newItem.save() return redirect('/') @login_required(login_url='/login') def login_user(request): if request.method == 'POST': username = … -
Django server won't run: This site can’t be reached127.0.0.1 refused to connect
I am trying to make an auction website for my CS50W project2: Commerce .When I try to run python3 manage.py runserver. There are 6 errors. I get that the system identified 6 errors: System check identified 6 issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/loader.py", line 259, in build_graph self.graph.validate_consistency() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auctions.0003_auto_20201114_0509 dependencies reference nonexistent parent node ('auctions', '0002_listing') please help -
Django admin and MTM relationships
I'm working with following scheme: class Session (models.Model): uuid = # uuid status = # charfield class Document (models.Model): session = models.ForeignKey(Session) signers = models.ManyToManyField(Signer, through='Signature', related_name='documents') class Signer(models.Model): uuid = # uuid class Signature(models.Model): signer = models.ForeignKey(Signer) document = models.ForeignKey(Document) I'm now trying to create a detail admin view where I can display: Session information List of documents in session Nested list per document for all signers in document Nested list per signer with all signatures for signer So far I came up with: @admin.register(Session) class SessionAdmin(nested_admin.NestedModelAdmin): search_fields = ("status", ) list_display = ("uuid", ) inlines = [DocumentInline] can_delete = False class InSignDocumentInline(nested_admin.NestedTabularInline): model = Document inlines = [ InSignSignerInLine, ] exclude = ['signers', ] class SignerInLine(nested_admin.NestedTabularInline): model = Document.signers.through But all that is showing is: Session with information List of documents in session Nested list of signatures in document (I would like to display the signers between the documents and the signatures) What am I missing? -
How to aceess list item in jinja
I have 2 list in my Django site. my views.py: def index(request): totalDBElement = [169, 2166, 5413, 635, 635] elementOrder = ['Rules', 'Questions', 'ParentChild', 'ChildList'] return render(request,'diagnosis/index.html', {'totalDBElement': totalDBElement, 'elementOrder' : elementOrder}) I wish to get something like this in my template: Rules: 169 Questions: 2166 ParentChild: 5413 ChildList: 635 my template: {% for i in len(totalDBElement) %} <h2> {{ totalDBElement[i] }} </h2> <h2> {{ elementOrder[i] }} </h2> {% endfor %} But it gives errors like: Could not parse the remainder: '(totalDBElement)' from 'len(totalDBElement)' Please suggest how can I fix this? I also wish to print -
django deployment on heroku issue (djongo not found)
remote: django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend. remote: Try using 'django.db.backends.XXX', where XXX is one of: remote: 'mysql', 'oracle', 'postgresql', 'sqlite3' remote: -
Django - How to get value from related model
I have my user model like this class User(AbstractUser): USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] last_name = models.CharField(max_length=48, blank=True) email = models.EmailField(unique=True) #Private=True Public=False account_type = models.BooleanField(default=False) And a preferences model for user class UserPreferences(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) leader_board_exclusion = models.BooleanField(default=False) reaction_count_visibility = models.BooleanField(default=True) How do I get the value leader_board_exclusion? Currently I'm doing this (Does this hit the database?) user_preference = UserPreferences.objects.get(user=user) print(user_preference.leader_board_exclusion) I was reading about selected_related and get_related and was thinking of a better way to do this -
Django chunked upload in IIS
I uploaded a program on which a django application is used for file uploading and used the chunk file uploads for it (with the blueimp fileupload on JS side). When I tested my application locally, it works. When I do it on the IIS production, I always get this error: POST http://URL/api/chunked_upload/ 500 (Internal Server Error) The logs in the IIS were not helpful either. JS Code: $('#fileUpload').fileupload({ url: window.location.href + 'api/chunked_upload/', dataType: "json", maxChunkSize: 100000, // Chunks of 100 kB formData: form_data, type: 'POST', add: function (e, data) { form_data.splice(1); calculate_md5(data.files[0], 100000); $("#submitButton").off('click').on("click", function () { showLoading() data.submit(); }); }, chunkdone: function (e, data) { // Called after uploading each chunk if (form_data.length < 2) { form_data.push( {"name": "upload_id", "value": data.result.upload_id} ); } }, done: function (e, data) { // Called when the file has completely uploaded let formInput; $.ajax({ type: "POST", url: window.location.href + 'api/chunked_upload_complete/', data: { csrfmiddlewaretoken: csrf, upload_id: data.result.upload_id, md5: md5 }, dataType: "json", success: function(data) { inputForm = document.getElementById('ddGraderForm') document.getElementById('id_formFile').value = data['file'] inputForm.submit() } }); }, }); Django urls urlpatterns = [ path('', views.webinterfaceViews, name='main'), path('api/chunked_upload_complete/', FastaFileUploadCompleteView.as_view(), name='api_chunked_upload_complete'), path('api/chunked_upload/', FastaFileUploadView.as_view(), name='api_chunked_upload'), ] Django view class FastaFileUploadView(ChunkedUploadView): model = fileUpload def check_permissions(self, request): # Allow non … -
accessing context variables that contain spaces
I have python dictionary, and I am passing its values to a html page to display them. i am able to access the values of the dictionary by using {{ value.xxx }} where the xxx is the element of the dictionary. the values appear on the screen no problem for name, age & height below. However the skill set component doesn't appear because of the space in the text. How can i set it so that i can access the elements that contain a space, like the skillset value below. I have tried adding an underscore such as {{ value.skill_set }} but that doesn't seem to work. Dictionary: dict = {1: {'name': 'John', 'age': '27', 'height': '160', 'skill set': 'running'}, 2: {'name': 'Marie', 'age': '22', 'height': '170', 'skill set': 'swimming'}} Html: <table class="u-full-width" id="table2"> <thead > <tr> </tr> </thead> <tbody> {% for key,value in dict_items.items %} <tr> <th scope="row" style="text-align:center">{{ key }}</th> <td style="text-align:center">{{ value.name }}</td> <td style="text-align:center">{{ value.age }}</td> <td style="text-align:center">{{ value.height }}</td> <td style="text-align:center">{{ value.skill set }}</td> </tr> {% endfor %} </tbody> </table> -
Tastypie/Django: Populating a relational database in a single Resource
I'm trying to populate a relational database in Django with Tastypie. I've prepared JSON which'll be sent to the API and then populates the database. This is what I'm trying to populate first, before I work on the rest of the database. This section is the initialisation. Here are the resources of the tables above: class EnvironmentResource(ModelResource): test_environment_id = fields.ToManyField(*other table in db*), 'environment_id') class Meta: queryset = TestEnvironment.objects.all() class SetInfoResource(ModelResource): set_info_id = fields.ToManyField(EnvironmentResource, 'set_info_id') class Meta: queryset = SetInfo.objects.all() class ConnectedDevicesResource(ModelResource): class Meta: queryset = ConnectedDevices.objects.all() I'm unsure on what endpoint I should sent my JSON to. Do I create a seperate resource like PopulateInitilisation and then list all the models that I'm populting? Something like this? class TestEnvironmentInitialisationResource(ModelResource): class Meta: resource_name = "initialisation" def deserialize(self, request, data, format='application/json'): print("deserialising") environment_model = Environment() connected_devices_model = ConnectedDevices() set_info_model = SetInfo() print("Models created from JSON data") Or do I need a resource that's an entry point and then it'll be populated with reverce relations? I know there's select_subclasses however I'm not sure if this is relevent. There's also hydrate_m2m but these relations are OneToMany. Therefore, I'm quite confused how I can go about this. -
When i hit the "PUBLISH COMMENT BUTTON" the comments does not get posted in my frontend in django
i am making a comment section in django but when i hit the comment section the comment does get published to the comment section of my website it just refreshed the page and does nothing but when i add a comment from my backend which is the admin section it works perfectly fine and get updated in my front end but the comment form in my blog posts details doesnt work, let me show some of my code views.py # this view returns the blog details and the comment section with the form def blog_detail(request, blog_slug): post = get_object_or_404(Blog, slug=blog_slug) # post = Blog.objects.filter(slug=blog_slug) categories = Category.objects.all() comments = post.comments.filter(active=True) new_comment = None if request.method == "POST": comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.name = request.user new_comment.save() else: comment_form = CommentForm() context = { 'post': post, 'comments': comments, 'comment_form': comment_form, 'new_comment': new_comment, 'categories': categories, } return render(request, 'blog/blog-details.html', context) forms.py class CommentForm(forms.ModelForm): # tags = forms.CharField(widget=forms.TextInput(attrs={'class': 'input is-medium'}), required=True) class Meta: model = Comment fields = ['email', 'body'] admin.py @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', 'post', 'created_on') list_filter = ('active', 'created_on') search_fields = ['approve_comment'] def approve_comment(self, request, queryset): queryset.update(active=True) models.py class Comment(models.Model): post = … -
django-form not displaying errors
I have the following form, its class looks like this: login_form.py class login_form(forms.Form): uname = forms.CharField(max_length=50,widget=forms.TextInput(attrs={'class':'form-control, form-inline'})) pwd = forms.CharField(max_length=60,widget=forms.TextInput(attrs={'class':'form-control, form-inline'})) I use a view called "xy_index.py" to instantiate it in: def xy_index(request): template = loader.get_template('xy_index/index.html') # create a form instance and populate it with data from the request: form = login_form() #check if logged in or not if request.user.is_authenticated: print("authinticated") print(request.user.username) print("user is:"+str(request.user)) # create a form instance and populate it with data from the request: return HttpResponse(template.render({'form':form},request)) else: print("not authinticated") # create a form instance and populate it with data from the request: return HttpResponse(template.render({'form':form},request)) Then I render it in my template: <!--form--> <form class="form-inline" action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="form-group"> {{ form.uname.errors }} <label for="{{ form.uname.id_for_label }}" class="form-label p_ult1">Username</label> {{ form.uname }} {{ form.pwd.errors }} <label for="{{ form.pwd.id_for_label }}" class="form-label p_ult1">Password</label> {{ form.pwd }} </div> <input type="submit" value="Login"> <a href="{% url 'reg' %}">Don't have an account? Register from here</a> </form> <!--end form--> Everything works fine, except for displaying the errors; it doesn't display at all. Could you tell me what's wrong? -
Issue with displaying data from database from array in django
I am implementing my first website in django and I want to display a table with data taken from MySQL database. I am having a problem with sending the list of arrays to the template. I always get 500 error. This is the fragment of my views.py: if request.method == 'GET': user = request.user saved_songs = [] for idx,s in enumerate(SavedSongs.objects.raw('SELECT * FROM MGCapp_savedsongs WHERE user_id = %s', [user.id])): song_name = s.song_name genre = s.genre source = s.source date = s.date.isoformat() saved_songs.append({'idx': idx, 'song_name': song_name, 'genre': genre, 'source': source, 'date': date}) for song in saved_songs: print(song['idx']) print(song['song_name']) print(song['genre']) print(song['source']) print(song['date']) return render(request, 'saved-history.html', context = {'saved_songs': saved_songs}) There must be a problem with template, because when I print the array to the console (as you can see above), everything works fine. My template: <table class="table table-hover" style="margin-top: 20px; "> <thead> <tr> <th></th> <th>Song name</th> <th>Genre</th> <th>Source</th> <th>Date</th> </tr> </thead> <tbody> {% for song in saved_songs %} <tr> <td> {{ song['idx'] }}</td> <td> {{ song['song_name'] }} </td> <td> {{ song['genre'] }} </td> <td> {{ song['source'] }} </td> <td> {{ song['date'] }} </td> </tr> {% endfor %} </tbody> </table> -
Memory store from cloud run create error Unable to create a new session key. It is likely that the cache is unavailable
I have an application deployed on Cloud Run. It runs behind an HTTPS Load balancer. I want it to be able to cache some data using memory store service. I basically followed the documentation to use a serverless vpc connector but this exception keeps poping: Unable to create a new session key. It is likely that the cache is unavailable. I am guessing that my cloud run service can't access memorystore. On Django I have: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": f"redis://{CHANNEL_REDIS_HOST}:{CHANNEL_REDIS_PORT}/16", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "IGNORE_EXCEPTIONS": True, }, "KEY_PREFIX": "api" } } where CHANNEL_REDIS_HOST is the IP from my memorystore primary endpoint and CHANNEL_REDIS_PORT is the port. When I run this command: gcloud redis instances describe instance_name --region region --format "value(authorizedNetwork)" it returns projects/my_project/global/networks/default. Then, on the VPC network, I clicked on 'default' and then on 'ADD SUBNET'. I created my subnet with IP Address range 10.0.0.0/28. Maybe the problem comes from this step as I do not get a lot about this all IP Communication thing.. When I run this command: gcloud compute networks subnets describe my subnet purpose is PRIVATE as intended and network is https://www.googleapis.com/compute/v1/projects/my_project/global/networks/default. So I think that my memorystore instance and my … -
Weasyprint gives Fontconfig error when used with Django
I'm trying to make an application which downloads a pdf report with data from a form. The form is done by Django, the pdf by WeasyPrint. But they don't seem to work together. This works fine as code outside of Django: from weasyprint import HTML HTML(string='test').write_pdf("./report.pdf") However, when part of a Django response, like this: def result(request): buffer = io.BytesIO() HTML(string='test').write_pdf(buffer) buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='report.pdf') I get Fontconfig error: Cannot load default config file and my Django server closes. Any ideas how to solve this? I'm on Windows 10, python 3.7, installed the latest versions of Django and WeasyPrint (and their dependencies) via conda. -
Connection cannot be made using celery and django
I learnt how to send email using Django and Celery. I wrote the entire code pretty well. Then when I ran that, I faced an unusual error called ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it. I don't use any firewall or protection system in my system I'm new to this so I might even make an error in the command prompt so if there is no error please tell me what to enter correctly in the command prompt too I ran the redis server and I feel like it's working pretty fine This is the entire error I faced -------------- celery@LAPTOP-O88PS3KM v5.2.1 (dawn-chorus) --- ***** ----- -- ******* ---- Windows-10-10.0.22000-SP0 2021-11-18 19:15:24 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: djangocelery:0x2a44256a4c0 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 12 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . djangocelery.celery.debug_task . main_app.tasks.test_func . send_mail.tasks.user_send_mail [2021-11-18 19:15:24,519: INFO/MainProcess] Connected to redis://127.0.0.1:6379// [2021-11-18 19:15:24,525: INFO/MainProcess] mingle: searching for neighbors … -
referencing an ID field of a form in Views.py
I am trying to send the url of a model entry to via e-mail when my form is submitted However when I reference my form.id like so + `'(http://localhost:8000/zipherJobCards/viewJobCard/'+form.cleaned_data['id']+')',` I get the following error KeyError: 'id' Is there any right way to reference the id of an entry like this ? Please see the full send_mail function here def jobCard(request ): form = jobCardForm() if request.method == 'POST': form = jobCardForm(request.POST) if form.is_valid(): form.save() send_mail( 'ZTS JOB CARD' + form.cleaned_data['jobNumber'], 'A new job card has been loaded for ' + form.cleaned_data['customerName'] + ' with a Total Cost of ' + form.cleaned_data['totalCostOfJob'] + '(http://localhost:8000/zipherJobCards/viewJobCard/'+form.cleaned_data['id']+')', 'it.zipher@gmail.com', ['it@zipher.co.za'], fail_silently=False, ) return redirect('home') else: print(form.errors) content = {'form':form} return render(request, 'main/jobCard.html', content) -
Django DRF serializer how to get the latest object of foreignKey value
How can I grab only the latest Benchmark for each provider? Right now it grabs all of them, but I only need the latest one to be serialized. How can I achieve this? Models.py class Node(models.Model): node_id = models.CharField(max_length=42, unique=True) wallet = models.CharField(max_length=42, null=True, blank=True) earnings_total = models.FloatField(null=True, blank=True) data = models.JSONField(null=True) online = models.BooleanField(default=False) version = models.CharField(max_length=5) updated_at = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Benchmark(models.Model): benchmark_score = models.IntegerField() benchmarked_at = models.DateTimeField(default=timezone.now) provider = models.ForeignKey(Node, on_delete=models.CASCADE) Serializer.py class BenchmarkSerializer(serializers.ModelSerializer): class Meta: model = Benchmark fields = ['benchmark_score', 'benchmarked_at'] class NodeSerializer(serializers.ModelSerializer): benchmark_set = BenchmarkSerializer(many=True) class Meta: model = Node fields = ['earnings_total', 'node_id', 'data', 'online', 'version', 'updated_at', 'created_at', 'benchmark_set'] -
When i make a post and hit the "PUBLISH BUTTON" is shows a "Blog" Object is not iterable error
I have tried many ways using filter, since get tried to get a single object but it still does work. When i make a post from my admin section everything works fine but when making the post from my front end using a form it creates the posts then shows me object is not iterable "NOTE: the posts get created perfect well" but i get the iterable error and also slug does not auto populate in the frontend automatically as it does in the backend admin section. Any help would be greatly usefull and make my work faster. let me show some of my code views.py #this is for allowing user to create a new post from the frontend def blogpost(request): if request.method == "POST": form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.creator = request.user form.save() messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!') else: form = BlogPostForm() context = { "form": form } return render(request, 'blog/AddPost.html', context) #this is for listing all the blog posts def BlogList(request): posts = Blog.objects.filter(status='published').order_by('-created').values() categoriess = Category.objects.all() context = { 'posts': posts, 'categories': categoriess, } return render(request, 'blog/bloghome.html', context) # This is view for blog … -
How to forbid recreating docker containers with docker-compose up
I need your help! I started using docker this week, launched all containers for a new Django project. In this project there are several databases, python, django web server + redis, celery, etc. These all are served by separated docker containers and are launched by docker-compose up command. This is my probjem: when I type docker-compose up in the console, it starts all services. Then I need to restore my databases dumps for each database (it takes about an hour). But when I use pycharm tools for docker-compose, it recreates some containers. And also it recreates all my postgres databases with ALL MY DATA! Sometimes is doesn't recreate containers and I can do my job, but if I do any wrong move -then docker-compose erases my databases! I have tired to restore them! Is there way to protect containers from erasing, to forbid recreate my postgres containers? PS: I've also tried to export postgres containers to .tar file, but when I import it back, database insight the container is ok and container importing is faster than restoring data from sql, but metadata of docker image is different, so I can't use it. Please, give me any ideas) -
Export multiple csv file - Django
I would like to export one csv for each of my product. How can I do that? Currently it's export only the first file ... import csv products = Product.object.all() for product in products: response = HttpResponse(content_type='text/csv', charset='utf-8') response['Content-Disposition'] = 'attachment; filename=product.csv' writer = csv.writer(response, delimiter=';') writer.writerow([product.Name, product.Quantity]) return response