Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Editing a Model using templates in django
before updating the update.html form I get null constraint Error how do update my note in my app when i try to update Note model i get this error Request URL: http://127.0.0.1:8000/list Django Version: 2.0.7 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: TakeNotes_note.title In views.py def see(request): if request.user.is_anonymous == False: # lIST OF THE NOTES notes = list(Note.objects.filter(user = str(request.user))) context = {"notes":notes} if request.method == 'POST': # GET THE NOTE REQUESTED note_req = request.POST.get("note_req") if request.POST.get("form_type") == note_req: # CHECK THE DETAILS OF THE NOTED for i in context['notes']: if i.title == note_req: deets = {'note': i} return render(request,'read.html',deets) # Updating the note elif request.POST.get("form_type") == "EDIT": print("Editing", ) for i in context['notes']: if i.title == note_req: deets = {"note":i} if request.method == "POST": # Here is my problem newTitle = request.POST.get("title") newNote = request.POST.get("note") print(newTitle, newNote) i.title = newTitle i.note = newNote i.save() return render(request,"Update.html",deets) #missing Update # Deleting the note elif request.POST.get("form_type") == "DELETE": for i in context['notes']: if i.title == note_req: i.delete() return redirect("/") return render(request,'UserIndex.html',context) else: return redirect("/") in Update.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Update Note || {{ … -
Upload profile image from React to Django
Im trying to upload a image from my front-end (React) to Django, but i got a error, Bad request, problably becouse the serializer are not accepting the Image data. This is how the data reach the backend <QueryDict: {'id': ['1'], 'image': ['[object Object]']}> This is my view. class ProfilePictureView(APIView): parser_classes = [MultiPartParser, FormParser] def post(self, request): print(request.data) ipdb.set_trace() serializer = ProfilePictureSerializers(data=request.data) if serializer.is_valid(): try: picture = User.objects.get(id=request.data['id']) picture.image = request.data['image'] picture.save() serializer = ProfilePictureSerializers(picture) return Response(serializer.data, status=status.HTTP_200_OK) except: return Response({"Detail": "Not found"}, status=status.HTTP_404_NOT_FOUND) else: return Response(status=status.HTTP_400_BAD_REQUEST) This is my model. def upload_to(instance, filename): return 'media/{filename}'.format(filename=filename) class User(AbstractUser): image = models.ImageField(_("Image"),null=True, blank=True, upload_to=upload_to, default='media/default.png') The Serializer. class ProfilePictureSerializers(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'image') And my requisition on the frontend. const config = {headers: {'content-type': 'multipart/form-data'}}; export const ProfilePictureThank = (UserData, setError) => (dispatch) => { let formData = new FormData(); formData.append("id", UserData.id) formData.append("image", UserData.image) axios .post( `${url_local}/api/profile/picture/`, formData, config) .then((info) => { dispatch(postUserProfilePicture(info.data)); }) .catch((error) => { setError(true); dispatch(postUserProfilePicture(error)); }); }; And here the profile app. const UserData = { id: userId, image: photo } const changeImage = async (e) => { setPhoto({image: e.target.files}) dispatch(await ProfilePictureThank( UserData, setError)); }; <section className="profile-picture-container"> <div className="profile-picture-item"> <img className="profile-photo" src={photo} />; … -
Could not find C:\Users\xerxe\Desktop\bioclin\compose\local\django:
After I run this in the terminal: docker-compose -f local.yml build I get this error: could not find C:\Users\xerxe\Desktop\bioclin\compose\local\django: CreateFile C:\Users\xerxe\Desktop\bioclin\compose\local\django: The specified path could not be found. -
xhtml2pdf problem with converting html file with polish characters
I am trying to make invoices by creating html file and convert it to pdf and than send as http response. The problem is that those invoices contains polish characters which UTF-8 does not display example. I have tried to use ISO-8859-2 to display them, but than I am getting error: ('charmap' codec can't encode characters in position 1159-1163: character maps to ) error. utils.py: from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument( src=BytesIO(html.encode('ISO-8859-2')), dest=result, encoding='UTF-8' ) if pdf.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return HttpResponse(result.getvalue(), content_type='application/pdf') views.py: class GeneratePDF(View): def get(self, request, pk=None): "getting data here" pdf = render_to_pdf("invoice.html", data) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Sales_Invoice_%s.pdf" % ("name") content = "inline; filename=%s" % (filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" % (filename) response['Content-Disposition'] = content return response return Response(status=rest_status.HTTP_404_NOT_FOUND) Pip freeze: appdirs==1.4.4 arabic-reshaper==2.1.3 asgiref==3.4.1 autopep8==1.5.7 backcall==0.2.0 backports.entry-points-selectable==1.1.0 beautifulsoup4==4.10.0 certifi==2021.5.30 cffi==1.14.6 charset-normalizer==2.0.5 colorama==0.4.4 cryptography==3.4.8 debugpy==1.5.0 decorator==5.1.0 defusedxml==0.7.1 distlib==0.3.2 Django==3.2.7 django-allauth==0.45.0 django-cors-headers==3.8.0 django-rest-auth==0.9.5 djangorestframework==3.12.4 entrypoints==0.3 filelock==3.0.12 future==0.18.2 html5lib==1.1 idna==3.2 ipykernel==6.4.1 ipython==7.28.0 ipython-genutils==0.2.0 jedi==0.18.0 jupyter-client==7.0.6 jupyter-core==4.8.1 matplotlib-inline==0.1.3 mysqlclient==2.0.3 … -
Django : Media URL not showing on the browser
I want to get media django link but I got error 404 on my browser (Chrome) and 200 status code on Terminal models.py from django.db import models from django.utils import timezone from django.utils.translation import gettext as _ from simple_history.models import HistoricalRecords from django.conf import settings from .formatChecker import ContentTypeRestrictedFileField import os class Contrat(models.Model): nom = models.CharField(max_length=15) prenom = models.CharField(max_length=20) telephone = models.CharField(max_length=14, unique=True) telephone2 = models.CharField(max_length=14, unique=True, blank=True, null=True) date_de_naissance = models.DateField(_("date de naissance")) email = models.EmailField(max_length=128) class Record(models.Model): def content_file_name(instance, filename): ext = filename.split('.')[-1] filename = "%s_%s.%s" % (instance.contratSante.nom, instance.contratSante.prenom, ext) return os.path.join('enregistrements', filename) contratSante = models.ForeignKey(ContratSante, default=None, on_delete=models.CASCADE) record = ContentTypeRestrictedFileField(upload_to=content_file_name,content_types=['audio/mpeg', 'audio/mp3', 'audio/ogg'], max_upload_size=20971520, max_length=None) I got this from .formatChecker import ContentTypeRestrictedFileField from formatChecker.py script to check file size and extention from django.db.models import FileField from django.forms import forms from django.template.defaultfilters import filesizeformat from django.utils.translation import ugettext_lazy as _ class ContentTypeRestrictedFileField(FileField): """ Same as FileField, but you can specify: * content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg'] * max_upload_size - a number indicating the maximum file size allowed for upload. 2.5MB - 2621440 5MB - 5242880 10MB - 10485760 20MB - 20971520 50MB - 5242880 100MB - 104857600 250MB - 214958080 500MB - 429916160 """ def … -
Django UpdateView generating 'GET' request instead of 'POST'
I'm following along a book called Django for Beginners and creating a project which displays newspaper articles. Part of the functionality is being able to edit those articles. I've followed along as closely as I could but I'm still getting an error when hitting the 'Update' button: My urls.py from django.urls import path from .views import (ArticleListView, ArticleUpdateView, ArticleDetailView, ArticleDeleteView) urlpatterns = [ path('<int:pk>/edit/', ArticleUpdateView.as_view(), name = 'article_edit'), path('<int:pk>/', ArticleDetailView.as_view(), name = 'article_detail'), path('<int:pk>/delete/', ArticleDeleteView.as_view(), name = 'article_delete'), path('', ArticleListView.as_view(), name = 'article_list'), ] my views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView from django.urls import reverse_lazy from .models import Article # Create your views here. class ArticleListView(ListView): model = Article template_name = 'article_list.html' class ArticleDetailView(DetailView): model = Article template_name = 'article_detail.html' class ArticleUpdateView(UpdateView): model = Article fields = ('title', 'body') template_name = 'article_edit.html' class ArticleDeleteView(DeleteView): model = Article template_name = 'article_delete.html' success_url = reverse_lazy('article_list') My models.py: from django.db import models from django.conf import settings from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class Article(models.Model): title = models.CharField(max_length=225) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): reverse('article_detail', args=[str(self.id)]) … -
Upload large file from django to cloud storage
I have a django app on Cloud Run and I'd like to create an endpoint that will be called by another python script. This endpoint should save files to Google storage. The file size is 800Mb max. So when I try to do this I receive: 413 Request Entity Too Large. So from digging the internet I understood that I should use chunk file. But there is something I do not understand.. From this: https://github.com/django/daphne/issues/126 I understand that daphne is now able to receive large body in request. So, I thought that, even receiving a big file Django was managing to chink it and send it piece by piece. I am curious, Is there anyway to do what I want other than doing manual chunk ? For now I added this to my settings: GS_BLOB_CHUNK_SIZE = 524288 DATA_UPLOAD_MAX_MEMORY_SIZE = 26214400 DATA_UPLOAD_MAX_MEMORY_SIZE = 26214400 and I simply use generics.ListCreateAPIView with default value for file upload handler. -
Update Django translations in production
I'm updating the translations file in production (.po file) if an user add some data. When is updated I run the command: from django.core.management import call_command call_command('compilemessages') and it works ok, by SSH I'm checkin that the .po and .mo is updated, but I can't get the new text translations. In my locale works fine, not sure what I have to do in production. My question is, how can I update the in-memory .mo file in prod ? -
Django:different html page if form is submitted
I'd like my html page to not show anymore the form once it is submitted by my user and instead I'd like to show a page with a message that say that the form was already submitted. I thought to use the registration date to determinate whatever the form is submitted or not but this is the error I'm getting when the form is not submitted 'NoneType' object has no attribute 'registration_date' while the code works if there is already a form submitted. I aso don't know if it good to use the presence of the absence of the registration date to determinate if the form is submitted, I've added the profile_submitted BooleanField in my models file but I'm not able to switch it to true and use it. models.py class UserProfile(models.Model): user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) gender = models.CharField(max_length=120, choices=gender_choice) birthdate = models.DateField() age = models.CharField(max_length=2) phone = models.CharField(max_length=10) email = models.EmailField() registration_date = models.DateField(default=datetime.today(), blank=True) profile_submitted = models.BooleanField(default=False) view.py def view_profile(request): profile_is_submitted = UserProfile.objects.filter(user=request.user).first().registration_date is not None context = {'profile_is_submitted': profile_is_submitted } return render(request, 'page.html', context) page.html {% extends 'base.html' %} {% block content %} <div class="container"> <h1> Title </h1> {% if profile_is_submitted %} You have already … -
Play video associated with image when clicking the image
I have this code: <div class="video3"> <!-- <video src="{{ video.video.url }}" controls></video> --> {% if video.thumbnail %} <img src="{{ video.thumbnail.url }}" alt="{{ video.title }}" style="width:100px;"> {% else %} <span class="text-muted">Without thumbnail</span> {% endif %} <div class="top-left">{{ video.title }}</div> </div> {% endfor %} </div> I'd like to play the video {{ video.video.url }} in fullscreen when clicking the image (thumbnail) associated with the video. -
how to loop based on the each item quantity in django
here one item has item quantity as 2 and second item has item qty as 3 so total of 5 times the for loop should be iterated(i.e for first item 2 times and second item 3 times ) in context_dict when passing the data(i.e range) to template its is passing only last item quantity(i.e 3) so its printing both items 3times but actually i need is first item as 2 times and second item as 3times class PrintLabels(View): def get(self, request, id, value): client = request.user.client order = OtherOrder.objects.get(client=client, id=id) items = order.otherorderitem_set.all() items_list = [] for c in items: item_dict = {} item = c.item if c.item.season_interest: try: item_dict['season_interest'] = (',').join(eval(c.item.season_interest)) except: item_dict['season_interest'] = (',').join(c.item.season_interest.split(';')) if c.item.summer_foliage_colour: try: item_dict['summer_foliage_colour'] = (',').join(eval( c.item.summer_foliage_colour)) except: item_dict['summer_foliage_colour'] = (',').join(c.item.summer_foliage_colour.split(';')) if c.item.exclude_intolerant: try:s item_dict['exclude_intolerant'] = (',').join(eval(c.item.exclude_intolerant)) except: item_dict['exclude_intolerant'] = (',').join(c.item.exclude_intolerant.split(';')) if c.item.item_name: item_dict['item_name'] = c.item.item_name if c.item.categories: item_dict['categories'] = c.item.categories if c.item.part_number: item_dict['part_number'] = c.part_number if c.batch_number: item_dict['batch_number'] = c.batch_number if c.item.common_name: item_dict['common_name'] = c.item.common_name if c.item.flower_colour: item_dict['flower_colour'] = c.item.flower_colour if c.item.growth_rate: item_dict['growth_rate'] = c.item.growth_rate if c.item.date_purchased: item_dict['date_purchased'] = c.item.date_purchased if c.ready_date: item_dict['ready_date'] = c.ready_date if c.due_date: item_dict['due_date'] = c.due_date if c.item.tree_type: item_dict['tree_type'] = c.item.tree_type if c.quantity: item_dict['quantity'] = c.quantity items_list.append(item_dict) template = … -
Django How to display a link from user input form safely
I have an model (posts) that is tied to a form that when a certain character is used it creates a link to another portion of the web app. The user can enter several of these characters/links to different areas of the webpage in one post then I want to display all of the users posts to the user in a list looping over the model that stores the link. However, how can I do this while maintaining security? I do not want to allow the user to enter in HTML and it be rendered. For example: User enters form information: "Hello this is a @test and @about is a test too" User selects submit button and background magic to get the words test and about and convert them into links to take the user to the test and about pages in the web application. Display all of the inputs/posts that have been created: "Hello this is a @test and @about is a test too" I know that I can use the safe tag and just store the HTML link in the model and call like normal but since this is from user input I don't want to allow them … -
Displaying a dictionary value from django model in a html
I have a django model that consists of a JSONField(). What I am trying to do is pass the details of this field to html, by the form of a context variable. The JSONField() stores a dictionary. For some reason the I only the first part of each dictionary element shows up in the presented html file. Models.py: class WholeValues(models.Model): eb_top_items_list = models.JSONField() Main.py #updating JSONField() values with a dictionary eb_numbers_for_upload = WholeValues.objects.all() eb_numbers_for_upload.update(eb_top_items_list=df_eb_values.head(n=6).to_dict()) html <ul> {% for item in eb_top_items %} <ul> {{ item }}</ul> {% endfor %} </ul> So the dictionary that is in my .JSONField() looks as follows {'ElectricBikeA': 13, 'ElectricBikeB': 12, 'ElectricBikeC': 11, 'ElectricBikeD': 11, 'ElectricBikeE': 7} However displayed on the page is only the text part of the dictionary. what is displayed is missing the number values. All it has is ElectricBikeA, ElectricBikeB....etc So i guess the real question is how can I get a context variable to show the values of the dictionary as well as the name? -
django - restrict visibility of divs for specific user group
I have created a blog app in Django framework. I have set up a login, logout, and sign up authentication system so authorized users can see everything and unauthorized can see only the home page. I am using django cms so people can add and edit content on website. I created 2 groups of users on admin page: managers and editors. Managers can edit, delete and add posts and editors can only edit posts. I'd like to apply something like this but directly on HTML pages and limit elements in my Blog posts (DetailvedView pages) for editors. I have 2 divs in my blog post page. First div(class='everyone') is visible for everyone and the second div (class='managers') is visible only for managers group? In other words, first 50% of the page is visible for everyone so for managers and editors group and 100% of the page is vsible only for managers group. How can I achieve something like that? -
The current path didnt match any of these Error when adding a link to a button
Been trying to add a link and it keeps sending me errors although the templates are working. Views.py def store(request): context = {} return render(request, 'store/store.html', context) def cart(request): context = {} return render(request, 'store/cart.html', context) def checkout(request): context = {} return render(request, 'store/checkout.html', context) Urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')) ] main.html <a class="nav-link" href="{$ url 'cart' %}">Store <span class="sr-only"> (current)</span></a> <a class="nav-link" href="{$ url 'store' %}">Store <span class="sr-only"> (current)</span></a> <a class="nav-link" href="{$ url 'checkout' %}">Store <span class="sr-only"> (current)</span></a> the url route sends me an error but I can access to the templates by 127.0.0.1:8000/cart and 127.0.0.1:8000/ works for store and 127.0.0.1:8000/checkout works for checkout. but I can not access thru the links -
Implementing Third Party API in Django
I am currently working on a project where I am consuming a third party API. In my views.py I have two views, the first is a FormView called GetShipmentRates that displays a form to the user, validates the form, makes an API call to get shipment rates using the form data and then redirects to the second view where the response from the API will be displayed. Here is the code: class GetShipmentRates(FormView): template_name = 'PartShipper/GetPitneyBowesShipmentRates.html' form_class = ShipmentForm success_url = reverse_lazy('PartShipper:view_rates') def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): return super().post(self, request, *args, **kwargs) def form_valid(self, form): return super().form_valid(form) class DisplayRates(TemplateView): template_name = 'PartShipper/DisplayRates.html' def get(self, request, *args, **kwargs): return super().get(self,request,*args, **kwargs) def post(self,request,*args, **kwargs): return super().post(self,request,*args, **kwargs) Here is where I am lost - I want to know which method should call the API request, should it be handled in the form_valid() method of my FormView, or maybe the post method of my FormView (Note that if I make the API request in the post method then this happens before the form is validated which is probably not ideal). I was also thinking of handling the API request in the second view … -
Not able to Crawl HTTPS web pages with Scrapy
I have a web scrapper which works without any issues locally but it's not able to crawl HTTPS web pages on the production server (CentOS). FYI. everything works as expected when I run the script through the command line (i.e. python scan.py) but I'm getting below errors when I run crawler from Django view. I use the Apache webserver on CentOS. (Also, it works fine in my local Django setup) I'm getting the below error when trying to crawl HTTPS web pages [scrapy.core.scraper] ERROR: Error downloading <GET https://validurl.com/> Below is the full error log Traceback (most recent call last): [Wed Oct 20 08:55:14.843638 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] File "/var/www/rocket/venv/lib/python3.6/site-packages/twisted/internet/defer.py", line 1658, in _inlineCallbacks [Wed Oct 20 08:55:14.843643 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] cast(Failure, result).throwExceptionIntoGenerator, gen [Wed Oct 20 08:55:14.843647 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] File "/var/www/rocket/venv/lib/python3.6/site-packages/twisted/internet/defer.py", line 63, in run [Wed Oct 20 08:55:14.843652 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] return f(*args, **kwargs) [Wed Oct 20 08:55:14.843656 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] File "/var/www/rocket/venv/lib/python3.6/site-packages/twisted/python/failure.py", line 500, in throwExceptionIntoGenerator [Wed Oct 20 08:55:14.843660 2021] [wsgi:error] [pid 2291806:tid 139906821093120] [remote 91.204.188.11:55294] return g.throw(self.type, self.value, self.tb) [Wed Oct 20 08:55:14.843664 2021] [wsgi:error] [pid … -
Django query with filter order by and distinct errors out
I have this query for receiving objects with a filter and our distinct for users ordered by date HallOfFame.objects.filter(group=group).order_by('-time').distinct("winner__id") It errors out with this raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("groups_halloffame"."winner_id") "groups... Got to know its a postgres issue -
DRF testing - create object with a many-to-many relation
I have the following model Project: class Project(models.Model): name = models.CharField(max_length=128) slug = models.SlugField(blank=True) assigned_to = models.ManyToManyField( User, blank=True, related_name="assignees") created_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now_add=False, auto_now=True) If I need to create a new project, all I need to do is supply the name alone. This works for both the Admin dashboard and DRF APIVIEW. But when I try to test the functionality with DRF with an API call, I get the error: [b'{"assigned_to":["This field is required."]}'] Although the field is not required. My test code below import datetime from marshmallow import pprint from rest_framework.test import APITestCase, APIClient from freezegun import freeze_time from accounts.models import User from .models import Project @freeze_time("2021-11-14") class ProjectTests(APITestCase): client = APIClient() project = None name = 'IOT on Blockchain' dead_line = datetime.date(2021, 11, 21) data = { 'name': name, 'dead_line': dead_line, } def create_user(self): username = 'test_user1' email = 'test.user1@gmail.com' password = '@1234xyz@' user_type = 'regular' data = {'username': username, 'email': email, 'password': password, 'user_type': user_type, } return User.objects.create_user(**data) def create_project(self): project = Project.objects.create(**self.data) user = self.create_user() project.assigned_to.add(user) return project def test_create_project_without_api(self): """ Ensure we can create a new project object. """ self.project = self.create_project() self.assertEqual(Project.objects.count(), 1) self.assertEqual(self.project.name, 'IOT on Blockchain') self.assertEqual(self.project.dead_line, datetime.date(2021, 11, 21)) … -
getting url error , on custom action in drf django
I am trying to test my custom action but I am getting a URL incorrect error don't know where I am going wrong about this , I have included these URLs in project directory but somehow custom action is not working class DocumentViewset(viewsets.ModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [permissions.IsAuthenticated] queryset = Document.objects.none() serializer_class = DocumentSerializer def get_serializer_class(self): if self.action == 'list': return DocumentSerializer if self.action == 'retrieve': return DocumentRetrieveSerializer return DocumentSerializer def get_queryset(self): queryset = Document.objects.filter(created_by=self.request.user).order_by('-id') return queryset @action(detail=False,methods=['get'],url_path='get_documents') def get_documents(self, request, pk=None): if pk == None: documents = self.get_queryset() else: documents = self.get_queryset() serialized_data = self.get_serializer_class(documents,many=True) data ={} data['serialized_data']=serialized_data.data data['id'] = pk return Response(data, status=200) router.register('document', DocumentViewset) router.register('notifications', NotificationsViewset) URL I am testing http://127.0.0.1:8000/api/document/1/get_documents -
Edit API POST Data before saving it in the Database
I've been stuck for 3 entire days on this. Frontend (Angular) is sending a Form data via POST: {name: 'Mario', surname: 'Super', location: 'New York', inputdatetime: '20-10-2021 15:52'} The "inputdatetime" is the custom date format "dd-MM-yyyy HH:mm" requested for the users and it is a string. I need to save it on my model via DRF: class Position(models.Model): id= models.AutoField(primary_key=True) name= models.CharField(max_length=20) surname= models.CharField(max_length=20) location= models.CharField(max_length=40) inputdatetime= models.DateTimeField() How can I convert 'inputdatetime' from a string in DateTimeField to be able to save it in the database creating a new record? So far I have tried to change DRF format date and Django format date to reflect "dd-MM-yyyy HH:mm", but the POST request went through only trying to pass the 'inputdatetime' as a ISOString, but, again, I need to do the "conversion" in the backend. -
Changed Django .py files not updating on nginx app
I'm updating a Django 1.7 application running on a Linux server with Nginx. I've updated my views.py and added some data to the payload sent to populate the template, to present in the resulting web page, but there's no update to the data being sent to the template. I made changes to the template files (html) to see if anything at all changes, and yes, the changes to the template were shown in the resulting web page. I figured that the -py files were being cached by something (web server maybe?) so I've restarted the nginx service again and again, but no change. The .pyc files did not update, so I removed them, restarted nginx, but no new .pyc files were generated. I ran python -m compileall in python 2, and new .pyc files were created, but the resulting web page still wasn't being updated. Bottom line... No changes made to my .py files are affecting the application being run. Changes to template files, javascript files and so on... no problem at all. Everything byt the .py files seem to work. I don't really know what more to present here to give more hints about my problem, so please ask. -
Django Multi-Social Authentication
I'm new to django. I'm seeking to to learn / develop rapidly and know stack overflow community has a lot of knowledge. Unfortunately I'm unable to find an answer to the problem I'm facing. Summary: Multiple social account authentication. Current State: I am using google authentication for user registration/login. Problem: I want user to link external accounts (i.e. instagram, facebook, coinbase) to their top level profile (as established through google authentication). Desired Outcome: A user will login using their google account. The associated accounts that have been linked to their profile will display. This means multiple accounts associated with their top level profile. I haven't written the code yet in hopes that an answer already exists. Any help is appreciated. -
Celery sync nodes of differents queue in a single prompt
I'm running Celery 4.4.2 and using differents queues and nodes on same machine. My objective is to separate and organize each Django Apps process. The queues are running ok on separetly nodes. The header example of each tasks are: @shared_task(name = "task1_App1", bind = True, result_extended = True, queue = 'App1') @shared_task(name = "task1_App2", bind = True, result_extended = True, queue = 'App2') And I run 2 Celery nodes in separetly prompt with: celery -A siteconfig worker-Q App1 -l info -n app1@%h -P gevent celery -A siteconfig worker-Q App2 -l info -n app2@%h -P gevent When I run a task in the node app1, it appears in the prompt running the node app2, with the message "app1 sync with app2". I want each node showing only its tasks, without sync to other node prompt. What options I can use? I'm using Win, Python 3.7.8 and Django 2.2. -
Django sessions for anonymous users on create Orders
I have views for add Order for user, it's working, and it's ok. But I need the same thing, but only for an anonymous user, through a session. I haven't worked with sessions, and I read the documentation, try it, but I can't. Please, write me, using my example in the else thread, how can I create an Order in a session for unauthorized users? def add_to_cart(request, pk): item = get_object_or_404(Item, pk=pk) if request.user.is_authenticated: if order = Order.objects.filter(user=request.user).first(): if order.products.filter(pk=product.pk).exists(): if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: order = Order.objects.create(user=request.user) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: ??? # for Anonymous user in session # ??? Any information, tips, and links to similar situations - I will be very grateful for any help.