Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i update an input and submit it
I Want if I click on the edit icon the text will appear in input and I can edit it and when I submit it will edit not created again. I did the click on edit icon the text will appear in input but when I submit its created as new, so how can I do that? here is a gif of what I have i want in submit will be created app.js function App() { const [tasks, setTask]=useState([]) const [title, setTitle]=useState("") const [changeTasks , setChangeTasks ] = useState(false) const [edit, setEdit]=useState(false) useEffect(() => { axios.get('/tasks') .then(data=>setTask(data.data)) .catch(err => console.log(err)) }, [changeTasks]); const addTask = (e) =>{ e.preventDefault() axios.post('/tasks/create', {title:title, completed: true}) .then(data => setChangeTasks(pre => !pre)) .catch(err => console.log(err)) // to empty input after submit setTitle("") if(edit === true){ // do axios.put, but its in other component how could i do that } } return ( <div className="relative flex min-h-screen bg-gray-200 flex-col justify-center overflow-hidden bg-gray-50 py-6 sm:py-12"> <h1 className="flex justify-center p-4 md:p-0 mx-px md:mt-4 md:mb-3 text-center font-extrabold text-transparent text-8xl bg-clip-text bg-gradient-to-r from-purple-800 to-pink-300"> To Do List </h1> <div className="relative bg-white px-6 pt-10 pb-8 shadow-xl ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-lg sm:rounded-lg sm:px-10"> <div className="p-2"> <figure className="mb-4"> <blockquote className="italic font-extralight text-slate-700 mb-5"> … -
is anybody who wish to help us to integrate payment subscriptions in django website
Hello I'm from AFRICA and also a young developer who want to integrate PAYSTACK into a django website. its hardest for a Django developer in africa to integrate any payment gateway into a django website. Because A lot of developer here in Africa are PHP Developer and even the company that provide this payment gateway are more focus on PHP and laravel developer. Is anybody who wish to help us Doing this thing in Django Please. I created a Developer Account in PAYSTACK I also Install Paystack by: pip install paystack and added it into my INSTALLED APPS like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'myschool', #crispy Module 'crispy_forms', #Bootstrap Module 'crispy_bootstrap5', 'bootstrap5', 'storages', 'paystack' ] and added my PUBLIC KEY and SECTRET KEY in settings.py file like this: PAYSTACK_SECRET_KEY = '' PAYSTACK_PUBLIC_KEY = '' the only problem i have is that i don't know how to design a views that will process the payment and also the template, as i'm a junior django web developer from Northern Part Of Nigeria Africa. remember that Stripe is not working in Africa, PayPal Business Account is not supported in Nigeria, but PERSONAL are supported. Selling a product … -
Making a query while consuming an API
Its my first time consuming an API instead of building one with a db. Using SpaceXdata I'm trying to retrieve the year that had most launches. I can use https://api.spacexdata.com/v3/launches to retrieve all the launches and use launch_year= as a param to retrieve all the launches in that year. But I don't know how to retrieve the year with most launches. Can someone helpe me? I don't know if I need to change my view or something in the request url. My view.py: def home(request): response = requests.get('https://api.spacexdata.com/v3/launches') launches = response.json() return render(request, "main_app/home.html", {"launches": launches}) -
logo':logo.image_tag(self) AttributeError: 'NoneType' object has no attribute 'image_tag'
from . import models def get_logo(request): logo=models.AppSetting.objects.first() data={ 'logo':logo.image_tag(self) } return data ` This is my coding part here it is showing error. Can anyone please help me to fix it? -
Authentication with Auth0, swiftUI, and Django Rest Framework
I am trying to add authentication via Auth0 to my app that uses Django Rest Framework for the API backend and swiftUI for the front end. I have successfully connected auth0 to both the backend and frontent (to DRF via this tutorial and to swift via this tutorial). However, I am struggling to connect the two. I want to figure out a way to use Auth0's universal login page yet still have the user data show up in my Django Rest Framework API. Do you know of a way to do this, or is there a better way to implement this type of user authentication in my app? Here is the swift code I have been using to create the Universal Login Page. I am wondering if maybe I have to add an API call to DRF once the Auth0 verifies the credentials, but I am not sure. Button("Login") { Auth0 .webAuth() .audience("https://waittimes/api") // the api in auth0 .start { result in switch result { case .success(let credentials): print("Obtained credentials: \(credentials)") // maybe use access token to send a request to my DRF API?? case .failure(let error): print("Failed with: \(error)") } } } -
Gitlab CI & Django: How to install custom package with pip
I have a Django project that have many dependencies and among those are several custom private Django package listed in our requirements.txt file at the project root. I want to setup simple CI that triggers our tests each time a commit is made. To do so I have written a simple .gitlab-ci.yaml file that tries to run those tests but I am having trouble installing our custom dependencies. They are listed in our requirements like follow: ... Django==3.2.12 ... -e git+ssh://git@gitlab.com/{organization}/{project}.git@{commit-sha}#egg={project} -e git+ssh://git@gitlab.com/{organization}/{project}.git@{{commit-sha}#egg={project} ... Note: All the mentionned projects lies under the same Gitlab organization Here is what my .gitlab-ci.yaml file looks like: stages: - test run-test: image: ubuntu:18.04 stage: test before_script: # installing python, pip & installing requirements - apt -y update - apt -y install apt-utils git net-tools - apt -y install python3.8 python3-pip - apt -y upgrade - python3 -m pip install --upgrade pip - cd servers/api - pip3 install -r ../requirements.txt script: - python3 manage.py test This obviously fails giving the following error: Obtaining {project} from git+ssh://****@gitlab.com/{organization}/{project}.git@{commit-sha}#egg={project} (from -r ../requirements.txt (line 32)) Cloning ssh://****@gitlab.com/{organization}/{project}.git (to revision {commit-sha}) to ./src/{project} Running command git clone --filter=blob:none -q 'ssh://****@gitlab.com/{organization}/{project}.git' /builds/{organization}/platform/servers/api/src/{project} Host key verification failed. fatal: Could not read from … -
Getting a 405 error when visiting a URL I set up
Building a drop in voice chat room using Twilio, following the tutorial outlined by Twilio I have added these as my ALLOWED_HOSTS in my settings.py: ALLOWED_HOSTS = [ ".ngrok.io", "127.0.0.1", "localhost" ] This is how my urls.py is setup: from django.urls import path from .views import RoomView, TokenView urlpatterns = [ path("rooms", RoomView.as_view(), name="room_list"), path("token/<username>", TokenView.as_view(), name="rooms"), ] My Views: @method_decorator(csrf_exempt, name="dispatch") class RoomView(View): def post(self, request, *args, **kwargs): room_name = request.POST["roomName"] participant_label = request.POST["participantLabel"] response = VoiceResponse() dial = Dial() dial.conference( name=room_name, participant_label=participant_label, start_conference_on_enter=True, ) response.append(dial) return HttpResponse(response.to_xml(), content_type="text/xml") class TokenView(View): def get(self, request, username, *args, **kwargs): voice_grant = grants.VoiceGrant( outgoing_application_sid=settings.TWIML_APPLICATION_SID, incoming_allow=True, ) access_token = AccessToken( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_API_KEY, settings.TWILIO_API_SECRET, identity=username ) access_token.add_grant(voice_grant) jwt_token = access_token.to_jwt() return JsonResponse({"token": jwt_token.decode("utf-8")}) my models.py: from django.db import models class Room(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=100) slug = models.CharField(max_length=50) def __str__(self): return self.name and apps.py: from django.apps import AppConfig class VoiceChatConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'voice_chat' This is what I have in my parent urls.py (the one I use for other routers on my app): urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), # path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('api/register', RegisterApi.as_view()), path('update_profile/<int:pk>/', views.UpdateProfileView.as_view(), … -
Calculate property with request data in Django
I have class Feedback in models in my django project. It has some charField, IntegerField.. and also custom property. Hovewer what I need is to have a property calculated from input value (from request query params). It means that it is calculated by each request. Because I want to provide this information with all attibutes and other properties of object feedback on list view. Thx for your advice. -
How to convert a models.IntegerField() instance to int?
I've read How to convert a models.IntegerField() to an integer(the poster actually need copy-constructor function).And I've searched for Google. But it doesn't help. what I want to do is: #In app/models.py class Foo: a1 = models.IntergeField() a2 = models.IntergeField() #.... #many else b1 = convertToInt(a1) * 3 + convertToInt(a2) *4 + convertToInt(a7) #calc by needing b2 = convertToInt(a2) * 2 + convertToInt(a3) + convertToInt(a5) #calc by needing #.... #many else #b(b is price actually) will be used in somewhere else.Its type need be int for programmer-friendly using any advice? P.S. English is not my first language.Please forgive my syntax mistakes. -
Python Firebase Admin SDK, Illegal Firebase credential provided
I'm trying initialising Firebase Admin SDK using .env file on a Django app and I get the following error: Illegal Firebase credential provided. App must be initialized with a valid credential instance the initialisation code: from dotenv import load_dotenv load_dotenv() # take environment variables from .env. firebase_admin.initialize_app({ "type": os.getenv("TYPE"), "project_id": os.getenv("PROJECT_ID"), "client_email": os.getenv("CLIENT_EMAIL"), "private_key": os.getenv("PRIVATE_KEY"), "client_id": os.getenv("CLIENT_ID"), "private_key_id": os.getenv("PRIVATE_KEY_ID"), "auth_uri": os.getenv("AUTH_URI"), "token_uri": os.getenv("TOKEN_URI"), "auth_provider_x509_cert_url": os.getenv("AUTH_PROVIDER_X509_CERT_URL"), "client_x509_cert_url": os.getenv("CLIENT_X509_CERT_URL"), }) -
Django SASS processor does not update CSS files in production
I am using django-sass-processor (https://github.com/jrief/django-sass-processor) in order to generate .css from .scss files. The css wiles were generated on the fly in production, based on the modified date of the scss file (as I understand it from the documentation). However, this on-the-fly-generation of files suddenly stopped working. I have moved my static folder to a different location, so I suspect that is a problem, but my regular static operations (collectstatic) works just fine - it's just the css file generation. Here are the relevant variables from my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'sass_processor', .... ] STATIC_ROOT = '/mnt/hd5/static/' STATIC_URL = '/static/' SASS_PROCESSOR_ROOT = '/mnt/hd5/static/css/' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', ] The following file is located in /mnt/hd5/static/css: stylesheet.scss If I look at the latest filedate it is indeed the latest version, being modified more recently than the .css files. When I run collectstatic (not even sure that is needed?), it doesn't pick up any modifications. Is there a glaring problem that can be seen above? Or alternatively is there a way I can record/view any error that is generated in the process? -
Django update bootstrap modal not updating untill refresh
Hello django bootstrap modal form works when i create new data gets populated and pop up closes automatically without refresh but when updating success message appears but you have to refresh the page to see the new data. Thank You. swgindex.htm {% block extrascripts %} <script type="text/javascript"> $(function () { // Create book button opens modal with id="create-modal" $("#create-swg").modalForm({ formURL: "{% url 'create_swimmer' %}", modalID: "#create-modal" }); var asyncSuccessMessage = [ "<div ", "style='position:fixed;top:0;z-index:10000;width:100%;border-radius:0;' ", "class='alert alert-icon alert-success alert-dismissible fade show mb-0' role='alert'>", "Success: Swimmer was updated.", "<button type='button' class='close' data-dismiss='alert' aria-label='Close'>", "<span aria-hidden='true'>&times;</span>", "</button>", "</div>", "<script>", "$('.alert').fadeTo(2000, 500).slideUp(500, function () {$('.alert').slideUp(500).remove();});", "<\/script>" ].join(""); function updateModalForm() { $(".update-swg").each(function () { $(this).modalForm({ formURL: $(this).data("form-url"), asyncUpdate: true, asyncSettings: { closeOnSubmit: true, successMessage: asyncSuccessMessage, dataUrl: "/swimminglist/", dataElementId: "#swg-table", dataKey: "table", addModalFormFunction: updateModalForm } }); }); } updateModalForm(); // Read and Delete book buttons open modal with id=".bs-modal" // The formURL is retrieved from the data of the element $(".bs-modal").each(function () { $(this).modalForm({formURL: $(this).data("form-url")}); }); // Hide message $(".alert").fadeTo(2000, 500).slideUp(500, function () { $(".alert").slideUp(500); }); }); </script> {% endblock extrascripts %} Urls.py path('swimminglist/', views.SWGIndex.as_view(), name="swimminglist"), path('create/', views.SWGCreateView.as_view(), name='create_swimmer'), path('update/<int:pk>', views.SWGUpdateView.as_view(), name='update_swimmer'), path('read/<int:pk>', views.SWGReadView.as_view(), name='read_swimmer'), path('delete/<int:pk>', views.SWGDeleteView.as_view(), name='delete_swimmer'), -
MySQL 8.0.27 not accepting django check constraints
I have seen a 2 years old similar question to this but the question did not specify the MySQL version and there is no answers to the question. I'm use the django constraint API to create a model that has 2 foreign keys but both of them cannot exist together and both of them cannot be null at the same time. The constraints look something like this: CheckConstraint(check=Q(type='campaign', campaign__isnull=False), name='check_campaign_data'), CheckConstraint(check=Q(type='trigger', trigger__isnull=False), name='check_trigger_data'), The type indicates which foreign key the model will be using. However, the following warning appears on my console: (models.W027) MySQL does not support check constraints. HINT: A constraint won't be created. Silence this warning if you don't care about it. I have seen that this is now supported for MySQL 8.0.16 or higher. This is the output of mysql --version in my terminal: mysql Ver 8.0.27 for Linux on x86_64 (MySQL Community Server - GPL) Why is this not working if this version of MySQL is supposed to support this feature? -
Save multiple objects serializers
I have multiple serializers objects that comes from the request as json file. I want to store them inside databases only if they are Valid (all of them must be VALID) def post_images(trip_id,data): data['trip']=trip_id serializer = TripImageSerializer(data = data) if serializer.is_valid(): serializer.save() return Response(status = status.HTTP_201_CREATED) return Response({'images':serializer.errors},status= status.HTTP_400_BAD_REQUEST) class Trip_apiView(generics.ListCreateAPIView): queryset= Trip.objects.all() serializer_class=TripSerializer def post(self, request): data = request.data dataImg=data.pop('trip_images') if serializer.is_valid(): instance = serializer.save() respo=post_images(instance.pk,dataImg) if respo.status_code==400: return respo return Response({'trip_images' :serializer.errors}, status= status.HTTP_400_BAD_REQUEST) this is JSON : { "id": 137, "trip_images": [ {"image_title":"image1","image_order":1}, {"image_title":"image2","image_order":2} ], "title": "dqw", "description": "nice", "start_date": "2022-02-08T12:00:00Z", "end_date": "2022-02-14T12:00:00Z", } -
After adding dj-rest-auth I get a sever error 500
After adding user authentication I have not been able to get data from my MySQL database, I get an error code 500 and Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. I think it might be something to do with my requests and after user authentication I need to add a token to make requests but I am unsure how to. I followed this tutorial: https://blog.devgenius.io/django-react-authentication-part-1-d351726b284d. Exact code can be found here as well as before and after. https://github.com/DoritoThePug/ToDoList/tree/bug%231 All of the 3rd party frameworks 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', 'corsheaders' Custom User from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): def __str(self): return self.email Fetch Request fetch("/api") .then(response => response.json()) .then( data => this.setState({ todoList: data }) ) As I said, this worked perfectly before I followed the tutorial and added user authentication, I can make requests to the database for user authentication register/logout/login perfectly just not get data from my api. More specific code can be found at the github link above. -
Nginx don't expose CORS headers for media files
I have a vuejs application consuming Django DRF API. All endpoints all working correctly with my current configuration. Except for media files. In Mozilla Developer tools -> Network -> Headers, I check that all API endpoints include cors headers and media files don't. I am using django-cors-headers with common configuration: CORS_ALLOW_ALL_ORIGINS = True ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', ... ] INSTALLED_APPS = [ ... 'corsheaders' ] I've tried with different CORS configuration, here in settings.py, as mentioned in several Stackoverflow questions, but nothing change the behavior. I suspect the problem is on NGINX. This is my configuration file: server { server_name my_domain; ... location /media { autoindex on; alias /home/myproject/media; } location / { proxy_set_header Host $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-Proto $scheme; proxy_pass http://localhost:8000/; } # these options are managed by Certbot, do i think it is ok. listen 443 ssl; ssl_certificate ... ssl_certificate_key ... include ... ssl_dhparam ... } server { if ($host = mydomain) { return 301 https://$host$request_uri; } server_name mydomain; listen 80; return 404; } I've also tried adding add_header Access-Control-Allow-Origin *;, but again, the cors headers are not exposed. What am I missing here? -
How to debug the Duplicate key tablename_columnname_*****
When updating python manage.py migrate I have this error (1061, "Duplicate key name 'shared_models_historicalmessagedelivery_message_title_4bf2c7cb'") I understand this means duplication error. So I truncated the shared_models_historicalmessagedelivery table but in vain. I would like to debug more, so what is the 4bf2c7cb it could be used as clue? -
Django MultiValueDictKeyError at /create/ 'howto-input'
I'm trying to make simple form that would add a comment, I'm not using the forms.forms of django, I'm doing the forms from HTML directly and i want to use ajax to submit the form my form simply has 1 file field and a publish button, everything seem finely coded but i get this MultiValueDictKeyError at /create/ 'howto-input' views.py def create(request): if request.method == "POST": content = request.POST['howto-input'] user = request.POST['howto-user'] topic = request.POST['howto-topic'] new_question = AskQuestionOnHowToTopic(user=user, content=content, topic=topic) new_question.save() messages.success(request, f'Published') success = "Posted Successfully!" return HttpResponse(success) def howtoTutorial(request, howtocat_slug, howto_slug): howtotut = HowToTutorial.objects.get(slug=howto_slug, howtocat=howtocat) context = { 'howtotut': howtotut, } return render(request, 'howto/howto-tutorial.html', context) urls.py path('create/', views.create, name="create") template.html <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <form id="howto-form"> {% csrf_token %} <input type="text" name="content" id="howto-input" /> <input type="hidden" name="user" id="howto-user" value="{{ request.user }}" /> <input type="hidden" name="topic" id="howto-topic" value="{{ howtotut }}" /> <button class="save_btn mt-2 mb-10" type="submit">Publish</button> </form> <script type="text/javascript"> $(document).on("submit", "#howto-form", function (e) { e.preventDefault(); $.ajax({ type: "POST", // url: '/how-to/<howtocat_slug>/<howto_slug>/', url: "/create/", data: { content: $("#howto-input").val(), user: $("#howto-user").val(), topic: $("#howto-topic").val(), csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(), }, success: function (data) {}, error: function (xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); }, }); }); </script> -
How to hide backend url in react.js
So i was making a social media app the front end in react.js and the backend is django. If a user presses on the follow button it will make this http request to https://localhost:5000/follow/username/usertobefollowed so any person can inspect the website and type this url to follow someone but i dont want it to be happen i only want the client side to access it. The url gets post method people can use softwares like workshop to send post to the url. how i can hide the url. OS - Windows Python Version - 3.10.0 NPM version - 8.1.3 -
Django: problem between id, foreignkey and views
I need help to understand a part of django. I can't understand the relationships between foreignkeys, or rather the relationships within relationships. Let me explain: I'm making a travel app. In each trip, there is the possibility to add an activity. These activities are unique per trip and are therefore linked via a Foreignkey. Each activity also has a unique address. These are also linked to the activities via a Foreignkey. I would like to do 2 things: Post each trip with these activities. For each of the activities, the addresses should be displayed. Display the lists of trips, showing the country where the activities take place "country" of "addresse" of "activities". # models.py class Adresse(models.Model): libelle = models.fields.CharField(max_length=100) numero = models.fields.IntegerField(null=True) street = models.fields.CharField(max_length=100) code = models.fields.IntegerField(null=True) city = models.fields.CharField(max_length=100, null=True) country = models.ForeignKey(Country, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return f'{self.libelle}' class Trip(models.Model): title = models.fields.CharField(max_length=100) traveller = models.ManyToManyField(Character) date_start = models.DateField(default=date.today) date_end = models.DateField(default=date.today) def __str__(self): return f'{self.title}' class Activity(models.Model): TRANSPORT = 'TRANSPORT' HEBERGEMENT = 'Hébergement' RESTAURATION = 'RESTAURATION' LOISIR = 'LOISIR' ROLE_CHOICES = ( (TRANSPORT, 'Transport'), (HEBERGEMENT, 'Hébergement'), (RESTAURATION, 'Restauration'), (LOISIR, 'Loisir'), ) category = models.CharField(max_length=30, choices=ROLE_CHOICES) trip = models.ForeignKey(Trip, null=True, blank=True, on_delete=models.SET_NULL) adresse = models.ForeignKey(Adresse, null=True, … -
Is there any way to run docker container using django endpoint request?
I want to run docker container using Django endpoint request. I have multiple docker containers which needs to be run after the Django endpoint request calls. Or any alternative suggestions are also welcome. -
Updating a form with image field using htmx and django
I have a model Post class Post(models.Model): content = models.TextField() image = models.ImageField(upload_to='posts',blank=True) and I have form for that model class PostModelForm(forms.ModelForm): class Meta: model = Post fields = '__all__' I'm using htmx and I have some partial templates inside my main template. this is my partial template form to update my post {% load i18n crispy_forms_tags widget_tweaks %} <form action="" class="mt-2 ml-2" hx-put="{% url 'posts:edit-post-form' post.id %}" hx-target="#PostContent-{{post.id}}" enctype="multipart/form-data"> {% csrf_token %} {% render_field form.content class="form-control" name="content" %} {% render_field form.image class="form-control" name="image" %} <button type='submit' class="btn btn-outline-info">{% trans "Update" %}</button> </form> and below you can check my view from django.http.multipartparser import MultiPartParser from django.http import QueryDict def edit_post_form(request,pk): try: post = Post.objects.get(pk=pk) form = PostModelForm(request.POST or None, request.FILES or None ,instance=post) if request.user.profile == post.author: if request.method == "PUT": data = QueryDict(request.body).dict() # print(request.META['CONTENT_TYPE']) # MultiPartParser(request.META, request, request.upload_handlers).parse() if form.is_valid(): form.save() return redirect("posts:edit-post-detail" , pk=post.id) else: print(form.errors) return render(request, 'posts/partials/edit_post_form.html',context = {'post':post,'form':form}) else: return redirect("posts:main-post-view") except ObjectDoesNotExist: return HttpResponse("This post has been deleted") Since I have a "multipart/form-data" when I print data data = QueryDict(request.body).dict() print(data) I'll see the output sth like the dictionary below {'------WebKitFormBoundary4ZEQZO2qHFj9tp7w\r\nContent-Disposition: form-data; name': '"csrfmiddlewaretoken"\r\n\r\nQu0zvB12321jnzcxdfdasd7ItP9x2tLqnLjjhudnhcARv4zMkqdmzksQFuk56uq\r\n------WebKitFormBoundary4ZEQZO2qHFj9tp7w\r\nContent-Disposition: form-data; name="content"\r\n\r\nnew\r\n------WebKitFormBoundary4ZEQZO2qHFj9tp7w--\r\n'} I tried to use MultiPartParser but I … -
Python Django redirect to external url with session cookies?
Is there any way to redirect from python django page to external url and different website with it's own session cookies like JSESSIONID? My django web app doesn't use any JSESSIONID but I am planning to keep another website's JSESSIONID's and redirect it from my web app with its JSESSIONID. I think it's kinda like OAuth methodology I want to build. If I can't do this, I think I need to build a little desktop app to do this only. But changing to this method is my worst case scenario. What do you think? Thx in advance... -
How to send requests from one service to another in docker swarm?
I need a piece of advice regarding a docker swarm architecture. I have 2 nodes, a manager and a worker. In my swarm I have 3 replicas of my backend (Django), 3 replicas of my frontend (React) and 1 of my PostgreSQL database. I don't have nginx or traefik or anything else besides that. For some reason, the routing doesn't work. Sending POST requests from my frontend to my backend returns ERR_NAME_NOT_RESOLVED. I tried fetching for http://my_backend_service_name:8000/, relying on the swarm to do the load balancing. I am sure I am missing something. but from everything I read I understood this should be possible without traefik, nginx or anything else. This is my docker compose stack file: services: frontend: image: xxxxxx command: npm start ports: - "3000:3000" stdin_open: true networks: - web_network env_file: xxxxx deploy: replicas: 3 restart_policy: condition: on-failure db: image: postgres:11 ports: - "5432:5432" command: "-c logging_collector=on" volumes: - ./database/postgres_data:/var/lib/postgresql/data/ networks: - data_network environment: - POSTGRES_USER=xxxxx - POSTGRES_PASSWORD=xxxxx - POSTGRES_DB=xxxx deploy: placement: constraints: - "node.role==manager" restart_policy: condition: on-failure delay: 5s max_attempts: 3 window: 120s web: image: xxxxx depends_on: db: condition: service_started command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - … -
Comment with replies in django
I am working on blog application in django and I added comment section section in blog but I am having problem show replies for parent comment. Models.py class Comment(models.Model): comment_text = models.TextField(("comment_text")) user = models.ForeignKey("account.User", related_name=("comment_user"), on_delete=models.CASCADE) post = models.ForeignKey("Post", related_name=("comment_post"), on_delete=models.CASCADE) parent = models.ForeignKey('self',related_name=("replies"), on_delete = models.CASCADE , blank= True ,null=True) timestamp = models.DateTimeField(("Comment Timestamp"), auto_now=False, auto_now_add=True) def __str__(self): return self.user.username blog.html <div Class ="container"> <h3><b>Comments...</b></h3> <div class ="row"> <div class = "col-8"> <div class ="row"> {% if not post.comment_post.all %} No comments Yet {% else %} {% for comment in post.comment_post.all %} {% if comment.parent is Null%} <br> <hr> <div class = "col-2"> <img class="rounded-circle" width="80" height="60" src="{{comment.user.profile_image.url}}"> </div> <div class ="col-10"> <strong>{{comment.user.first_name}} {{comment.user.last_name}}</strong> <span class ="float-end"><i class="far fa-clock"></i> {{comment.timestamp.date}}</span> <p>{{comment.comment_text}}</p> </div> {%endif%} {% endfor%} <hr> <br> {% endif %} <div> {{form|crispy}} <span class ="float-start">Post Comment as: <b>{{request.user.first_name}} {{request.user.last_name}} </b></span> <button type="button" class="btn btn-primary btn-sm float-end mb-2">Post comment</button> </div> </div> </div> <div class ="col-4 bg-info"> .... </div> </div> </div> views.py class PostDetailView(FormMixin,DetailView): model = Post form_class = CommentForm template_name = 'MainSite/blogpost.html' I cant think of anyway to show replies under parent comment. Thanks in advance and any advice will be helpful