Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Same Host multi app Nginx Gunicorn
Run multiple django applications on one server environment python3 nginx django2 I cannot run. always Bad Request (400) django app1 settings nginx settings /etc/nginx/conf.d/abc.conf server { listen 80; server_name .abc.co; rewrite ^ https: // $ server_name $ request_uri? permanent; } server { listen 443 ssl; server_name .abc.co; ssl_certificate /etc/letsencrypt/live/abc.co/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/abc.co/privkey.pem; ssl_protocols TLSv1; ssl_ciphers HIGH:! ADH:! MD5; ssl_prefer_server_ciphers on; location / static { alias /home/abc.co/static; } location / media { alias /home/abc.co/media; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for; proxy_set_header Host $ http_host; proxy_redirect off; proxy_set_header X-Forwarded-Proto $ scheme; } } gunicorn settings /etc/systemd/system/abc.service [Unit] Description = gunicorn After = network.target [Service] WorkingDirectory = / home / abc.co ExecStart = / usr / bin / gunicorn --bind 127.0.0.1:8000 config.wsgi: application [Install] WantedBy = multi-user.target django settings /home/123.co/config/settings.py ALLOWED_HOSTS = ['abc.co'] Check the access to the main domain with the above settings, and confirm that the code is working properly. From here, trying to build another django app on the same server and IP address failed. django app1 Setting 2 ↓ nginx settings /etc/nginx/conf.d/123.conf server { listen 80; server_name .123.jp; rewrite ^ https: // $ server_name $ request_uri? permanent; } server { listen 443 ssl; server_name. 123.jp; ssl_certificate … -
Django Template extends remote url
I have moved my email templating (.html) to an S3 bucket. I want to send an email using a base.html and the body so I can reuse all my template. However when trying it django can't find the template. Note: I am not using django-storage as for now but manually getting the template using Template class (see below codes). I tried two methods already: Using the full remote url https://s3-ap-southeast-1.amazonaws.com/xxxx in the extends tags Got an error message: TemplateDoesNotExist (even if it does exist) Using relative path: ../../assets/base.html in the extends tags Got an error message: do_extends 'NoneType' object has no attribute 'lstrip' # To get my template def _get_remote_template(self, email_template): url = "%s/%s" % (self.email_host, email_template) response = requests.get(url) assert response.status_code == 200 return Template(response.content.decode("utf-8")) base.html <div class="body-section"> <!-- import here the content body --> {% block body %} {% endblock %} </div> template_1.html (First method) {% extends "https://s3-ap-southeast-1.amazonaws.com/xxxx/assets/templates/base.html" %} template_1.html (Second method) {% extends "../../assets/templates/base.html" %} Do you have any ideas on how to achieve that, my main goal is to remove all emails templates from my django project. Appreciate your help! -
Django 1.11.7 --> 2.0 --> 2.2 migration - errors on runserver and Wall check
I am doing migration from Django 1.11.7 --> 2.0 --> 2.2 I am running though some errors and needs some help on how to solve this. Here are the error output https://gist.github.com/axilaris/2088f3dfc281a2be6f9461d6577ca8dd here are some excerpts of the error outout $python -Wall manage.py check --settings=railercom.settings.local .... /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/_bootstrap.py:219: ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__ return f(*args, **kwds) System check identified no issues (0 silenced). and $python manage.py runserver --settings=unrealpower.settings.local ..... File "/Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/unrealpowerenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "/Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/unrealpowerenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 124, in iter_modules_and_files if getattr(module, '__spec__', None) is None: SystemError: <built-in function getattr> returned a result with an error set -
How to get foreign object with minimal price
I have two classes Product and Offer class Product: ... name = models.CharField(max_length=255) ... class Offer: ... price = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) ... And I have to get the offer of a product with minimal price in single queryset. I know that I can get price like this: Product.objects.filter(...).annotate(minimal_price=Min('offer__price').values('minimal_price', ...) or product.offer_set.all().order_by('price').first() But I have to get offer in single query with product like this: Product.objects.filter(...).annotate(offer_with_minimal_price=Min('offer__price__but_return_offer_not_price').values('offer_with_minimal_price', ...) -
Image cropping with pillow and cropper and django isn't saving the cropped image?
So I followed this link to add cropping feature to the app I tried their approach by overriding the save method and it caused some errors in the view so I decided to make the cropping process happen in the view but the problem I don't get the cropped image even after providing the values of the crop function manually. if request.method == 'POST': form = forms.ImageForm(request.POST,request.FILES) if form.is_valid(): image = form.save(commit=False) x = form.cleaned_data['x'] y = form.cleaned_data['y'] w = form.cleaned_data['width'] h = form.cleaned_data['height'] im = Image.open(image.pre_analysed) cropped = im.crop((x, y, w+x, h+y)) resized_image = cropped.resize((300, 300), Image.ANTIALIAS) resized_image.save(image.pre_analysed.path) image.patient = patient messages.success(request,"Image added successfully!") image.save() and here's the form class ImageForm(ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = UploadedImages fields = ('pre_analysed', 'x', 'y', 'width', 'height', ) here's the problem I think the save function of Pillow isn't being called right so how can I call it or how can overwrite the original image with the new one? Is there an easier way to crop images? I took a look at Django-image-cropping and I think it has more than I ask I just want to crop the image and save … -
Dynamic content on page is not showing
I am trying to generate dynamic content on page with the onclick event of js but there is error in console "Uncaught SyntaxError: Unexpected identifier" html {% load static %} <head> <script type="text/javascript"> function myFunction() { // document.getElementById("demo").innerHTML = "Paragraph changed."; document.getElementById("demo").innerHTML = "{{ Malegender }}"; } </script> </head> <body> <div class="container mt-5"> <h1>Gender</h1> <hr> <h5>{{ mygender.as_p }}</h5> <h1 id="demo">Hello</h1> <div class="container"> <button type="submit" name="gender_submit" class="btn btn-success" onclick="myFunction()">Confirm</button> </div> </div> </body> views.py def Gender(request): gender_selection = GenderForm() male_detail = MaleForm() Male = False print("Value of male",Male) if 'gender_submit' in request.POST: male_detail = MaleForm(data=request.POST) Male = True print("Value of male d",Male) print("Value of male a",Male) return render(request, 'Gender.html',{"mygender":gender_selection,"Malegender":male_detail}) forms.py class MaleForm(forms.ModelForm): class Meta: model = GenderModel fields = ('genderMale','genderMale1','genderMale2','genderMale3','genderMale4') models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class GenderModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gender_choice=(('Male','Male'),('Female','Female'),) gender = models.CharField(max_length=6,choices=gender_choice,null=True,) genderMale = models.BooleanField(default=False) genderMale1 = models.BooleanField(default=False) genderMale2 = models.BooleanField(default=False) genderMale3 = models.BooleanField(default=False) genderMale4 = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: GenderModel.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.gendermodel.save() when I click on button the error on the console is showing. I am trying to display that … -
Is it possible to use the built-in LogEntry to track actions of every users not only in admin page? If so, how can I implement it?
I just recently knew about the built in LogEntry model in django, and I've tried to registered it in my admin page. What I want to happen is, for example, the admin added new User not using the django admin page but through the add page I made using some model forms in my site, how can i add data to LogEntry regarding that add action on my site? Thanks for your help! -
How to set initial value in the form
Hey guys how can i set initial value in my form field, let say the user click "BidForm" in the search form, i want the BidForm value will be the value of ProjectName in the other form... here's my code in my search views def search_views(request): project_list = ProjectNameInviToBid.objects.all() query = request.GET.get('query') if query: project_list = project_list.filter(ProjectName__icontains=query) context = { 'project_list': project_list } return render(request, 'content/search_views.html', context) and my other views def project_name_details(request, sid): majordetails = ProjectNameInviToBid.objects.get(id=sid) if request.method == 'POST': form = invitoBidForm(request.POST, request.FILES) form.fields['ProjectName'].initial = majordetails if form.is_valid(): form.save() messages.success(request, 'File has been Uploaded') else: form = invitoBidForm() args = { 'majordetails': majordetails, 'form': form } return render(request,'content/invitoBid/bacadmininvitoBid.html', args) my form.py class invitoBidForm(ModelForm): class Meta: model = InviToBid fields = ('ProjectName','NameOfFile', 'Contract_No', 'Bid_Opening', 'Pre_Bid_Conference', 'Non_Refundable_Bidder_Fee', 'Delivery_Period', 'Pdf_fileinvi',) and my models.py class ProjectNameInviToBid(models.Model): ProjectName = models.CharField(max_length=255, verbose_name='Project Name', null=True) DateCreated = models.DateField(auto_now=True) def __str__(self): return self.ProjectName class InviToBid(models.Model): today = date.today() ProjectName = models.ForeignKey('ProjectNameInviToBid', on_delete=models.CASCADE) NameOfFile = models.CharField(max_length=255, verbose_name='Name of File') Contract_No = models.IntegerField(verbose_name='Contract No') def __str__(self): return self.NameOfFile -
Loading "Search Page" produces "404 Page Not Found" page when querying data
I have a page ".com/listings" that loads well, but when I run a query through the form, it produces this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/listings/search?keywords=&city=Corpus+Christi Raised by: listings.views.listing It should render a ".com/listings/search" page. Previously I had it working beautifully, but after I successfully changed the url path of single listings page - "listings/listing" to a string from an integer, it caused this problem for my search page. Could be a coincidence, but I believe it could be connected. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='listings'), path('<str:listing_title>', views.listing, name='listing'), path('search', views.search, name='search'), ] views.py from django.shortcuts import get_object_or_404, render from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from .choices import price_choices, city_choices, bed_choices, bath_choices from .models import Listing from agents.models import Agent from contacts.models import Contact def index(request): listings = Listing.objects.order_by('-list_date').filter(is_published=True) paginator = Paginator(listings, 6) page = request.GET.get('page') paged_listings = paginator.get_page(page) context = { 'listings': paged_listings, 'price_choices': price_choices, 'city_choices': city_choices, 'bed_choices': bed_choices, 'bath_choices': bath_choices } return render(request, 'listings/listings.html', context) def listing(request, listing_title): listing = get_object_or_404(Listing, title=listing_title) context = { 'listing': listing, } return render(request, 'listings/listing.html', context) def search(request): queryset_list = Listing.objects.order_by('list_date') if 'keywords' in request.GET: keywords = request.GET['keywords'] … -
Django Rest Framework - How to Create a model with related objects
I would like to be able to POST to a Model with an array of related objects, but I can't figure it out how. Now I am able to retrieve information from these relations, but don't know how to POST. Django==2.2.4 django-rest-framework==3.10.3 models.py from django.db import models import datetime from django.utils.html import format_html_join from collections import Counter class Cliente(models.Model): def __str__(self): return self.nome nome = models.CharField(max_length=200) class Meta: ordering = ['id'] class Produto(models.Model): def __str__(self): return self.nome + ", Preço unitário: " + str(self.preco_unitario) nome = models.CharField(max_length=200) preco_unitario = models.DecimalField(max_digits=14, decimal_places=2, default=0.00) multiplo = models.IntegerField(blank=True, null=True) class Pedido(models.Model): cliente = models.ForeignKey(Cliente, models.DO_NOTHING, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % (self.pedido_id) def total(self): itens = ItensPedido.objects.filter(pedido=self.pk) valor = sum(Counter(item.preco * item.quantidade for item in itens)) return str(valor) class ItensPedido(models.Model): pedido = models.ForeignKey(Pedido, on_delete=models.CASCADE,related_name='itemspedido', null=True) produto = models.ForeignKey(Produto, on_delete=models.CASCADE, null=True) preco = models.DecimalField(max_digits=14, decimal_places=2, default=0.00) quantidade = models.IntegerField(default=1, null=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.pedido.pedido_id + ": " + self.produto.nome + ", preço: " + str(self.preco) + ", quantidade: " + str(self.quantidade) Then I have my serializers.py from .models import Produto, Cliente, Pedido, ItensPedido from rest_framework import serializers class ProdutoSerializer(serializers.Serializer): id = serializers.IntegerField() nome = serializers.CharField() preco_unitario = … -
How create form for comments with used django and ajax
I'm trying to make it possible to edit comments using DRF, my idea is that after clicking on the button a form pops up in which there are all the same fields for creating DRF, namely the field with the name of the comment and the comment context itself. But I get an error in the answer that my fields are empty. As far as I understand, editing the API is called immediately, thereby skipping the values in the filled fields. How can I fix this, with high probability I am sure that the error is somewhere in JS. Here is the browser response: post: ["This field is required."] text: ["This field is required."]. <p class="comment_text"> {{ comment.text|linebreaks }} </p> <div> <form id="edit" method="post" action="/api/albums/{{comment.id}}/edit/"> <input type="hidden" name="csrfmiddlewaretoken"> <input type="text" class="input_Text_post"></br> <input type="text" class="input_Text_text"></br> <button class="button_edit" value="{{ comment.id }}"> Send </button> </form> </div> $(document).ready(function() { $(".button_edit").click(function(){ var comment_id = ($(this).attr('value')); var $this = $(this); $this.toggleClass('button_edit'); if ($this.hasClass('button_edit')){ $this.text('Send comment'); } else { $this.text('Change comment'); } $('.input_Text_text').show(); $('.input_Text_post').show(); $('.comment_text').text($('.input_Text_post').val()); $('.comment_text').text($('.input_Text_text').val()); $('#edit').on('submit', function(event){ event.preventDefault(); $.ajax({ type: 'PUT', url: 'http://localhost:8000/api/albums/' + comment_id + '/edit/', headers: {"X-CSRFToken": $csrf_token}, data: { 'post': $('#input_Text_post').val(), 'text': $('#input_Text_text').val(), }, success: function(data){ console.log(data); } }); }) }); }); class … -
Issue getting django celery worker started on elastic-beanstalk
I am trying to get my celery worker running on elastic-beanstalk. It works fine locally but when I deploy to EB I get the error "Activity execution failed, because: /usr/bin/env: bash": No such file or directory". I am pretty novice at celery and EB so I haven't been able to find a solution so far. I am working on a windows machine and I have seen other people face this issue with windows and fix it by converting "celery_configuration.txt" file to UNIX EOL, however I am using celery-worker.sh instead but I converted it to a UNIX EOL which still didn't work. .ebextensions/celery.config packages: yum: libcurl-devel: [] container_commands: 01_mkdir_for_log_and_pid: command: "mkdir -p /var/log/celery/ /var/run/celery/" 02_celery_configure: command: "cp .ebextensions/celery-worker.sh /opt/elasticbeanstalk/hooks/appdeploy/post/ && chmod 744 /opt/elasticbeanstalk/hooks/appdeploy/post/celery-worker.sh" cwd: "/opt/python/ondeck/app" 03_celery_run: command: "/opt/elasticbeanstalk/hooks/appdeploy/post/celery-worker.sh" .ebextensions/celery-worker.sh #!/usr/bin/env bash # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` celeryenv=${celeryenv%?} # Create celery configuraiton script celeryconf="[program:celeryd-worker] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery worker -A backend -P solo --loglevel=INFO -n worker.%%h directory=/opt/python/current/app/enq_web user=nobody numprocs=1 stdout_logfile=/var/log/celery/worker.log stderr_logfile=/var/log/celery/worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. … -
Django connect vcenter and list VM
Can't get list of VM with rest API, i managed to get the authentication session but I don't know how to get the ger for the vm list. I'm looking fot days but i don't have solution, i stored my session to connect on vcenter but i don't know how to get to get the vm list. I try everything. def vcenter_api(request): is_cached = ('value' in request.session) context = {} if not is_cached: ip_address = request.META.get('HTTP_X_FORWARDED_FOR', '') response=requests.post ('https://192.168.74.130/rest/com/vmware/cis/session', verify=False,auth=HTTPBasicAuth(api_user, api_pass)) request.session['value'] = response.json() x = request.session['value'] vm = request.GET.get('https://192.168.74.130/rest/vcenter/vm/') context.update({ 'vm' : vm }) return render(request, 'ok.html', context) In the emplate it returns as a value 'none' if instead I take the value of x I get the authentication token. Please help me i don't understand. Thank you so much!!! -
Django admin.ModelAdmin autocomplete_fields on select fill an other field?
This is setup via de models.py and admin.py For simplicity, I got 3 models: Order, OrderRow (admin.TabularInline) and Product. The OrderRow has a price and Product also has a price. OrderRow is a admin.TabularInlinem and added (via inlines) to Order, and OrderRow has a relationship with Product. I can now add new Order, then add OrderRows and select a Product, works great. But what I want is that when the user selects a Product it also copies the price to the OrderRow (which can then overwritten by the user). Was gooien to the Django docs, but couldn't really find what I was looking for. Before I go built something myself that might be implemented already, what's would be the best way to do this? Any callback I can register or some hook I can use? Thanks! -
Implement search by two forms django
I want to implement search by two parameters form: home.html <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search..."> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>All locations</option> <option>RU</option> <option>Ukraine</option> <option>USA</option> </select> <button> Search </button> </form> When I click to "search" it's OK (I go to http://127.0.0.1:8001/search/?q=mos&q2=RU) But when I click "next", I receive http://127.0.0.1:8001/search/?city=2&q=mos&q2= but I need http://127.0.0.1:8001/search/?city=2&q=mos&q2=RU How can I fix this? <a href="/search?city={{ page_obj.next_page_number }}&q={{ query }}&q2= {{query}}">next</a> Full code: search_results.html <h1>Search Results</h1> <ul> {% for city in object_list %} <li> {{ city.name }}, {{ city.state }} </li> {% endfor %} </ul> <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/search?city={{ page_obj.previous_page_number }}&q={{ query }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="/search?city={{ page_obj.next_page_number }}&q={{ query }}&q2= {{query}}">next</a> {% endif %} </span> </div> views.py from django.shortcuts import render from django.views.generic import TemplateView, ListView from .models import City from django.db.models import Q from django.shortcuts import render, get_object_or_404 class HomePageView(ListView): model = City template_name = 'cities/home.html' paginate_by = 3 page_kwarg = 'city' def city_detail(request, pk): city = get_object_or_404(City, pk=pk) return render(request, 'cities/city_detail.html', {'city': city}) class SearchResultsView(ListView): model = City template_name = 'cities/search_results.html' paginate_by = 3 page_kwarg = 'city' … -
How can I stop Django server via command in cmd without click "CTRL + C"?
Im writing my desktop app on PySide2(its not important) for control Django project (run server and stop server on buttons). I realized only start server, but i cant add stop server, because stop server is click on buttons "CTRL + C" in cmd and i dont now how to interpret clicks on buttons into code or any answers for this question(( Here is an example for "RUN server" and I need some help for "STOP server" os.chdir(ui.lineEdit.text()) # Change directory os.system("python manage.py runserver") # Run server in this -
Django cannot delete custom field class; makemigrations throws AttributeError
Lead-up: I subclassed django.db.models.fields.CharField. Then used that custom field called myapp.models.QueryStringField in a model and made my migrations and migrated successfully. Then I changed my mind and decided to replace it with a normal CharField in my model, which I did (again with successfull migration). Problem: When I then deleted the QueryStringField class entirely from myapp.models and did makemigrations, it threw the following error (last lines shown here): File "C:\...\migrations\00....py", line 17, in Migration field=myapp.models.QueryStringField(max_length=255), AttributeError: module 'myapp.models' has no attribute 'QueryStringField' What can I do to fix this? I understand that this is technically correct, since the migration references a class that is not present, but surely this can be solved somehow. I am a little nervous about just deleting migration files. -
How can I give an error when someone edits there profile and changes the email to an email that already exists using django?
I want to give an error that an account with a email already exists, but it doesn't seem to work when a user edits there profile. Also, if the email isn't valid when submitting the form it it gives a value error: "The view accounts.views.edit_profile didn't return an HttpResponse object. It returned None instead." Here is the code: {% extends 'base.html' %} {% block head %} <link href="\static\accounts\css\forms.css" rel="stylesheet"> {% endblock %} {% block body %} <h3 style="text-align: center">Edit profile</h3> <form id="login-form" method="post"> {% csrf_token %} <input placeholder="Email" id="id_email" name="email" type="text" class="form-control" value="{{ user.email}}"> <input placeholder="First name" id="id_first_name" name="first_name" type="text" class="form-control" value="{{ user.first_name}} "> <input placeholder="Last name" id="id_last_name" name="last_name" type="text" class="form-control" value="{{ user.last_name}}"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p class=" label label-danger"> <div style="text-align: center"> {{ error }} </div> </p> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error }}</strong> </div> {% endfor %} {% endif %} <div style="text-align:center;"> <button type="submit" class="btn btn-outline-dark centerbutton">Save edits</button> </div> </form> {% endblock %} -
Strange looking Swedish characters in generated PDF
I am building backend for a system in Django and I am generating PDF files using ReportLab. Please notice that the dots and circle above some letters are moved to the right for some reason. Why does this occur? Font is Times New Roman. -
Delete/destroy method in django
I have a generic api view that I would like to use for both put, delete (and eventually, update) of records for a certain model, but I am fairly confused about the best practice for deleting a record in Django. Should I use the built-in delete method, or do I define my own? Do I process it as a DELETE or 'destroy' method on a GenericAPIView. I don't want to allow just anyone to delete a record, so I need to first validate that they are the same user that created the record. By some accounts, it sounds like Django allows you to delete a record with just authentication and the id. If true, how do I disable this behavior? Thanks for any code or guidance on these various questions. frontend.js const deleteRow = (id) => { alert(id) fetch(`${SERVER_URL}/api/v1/requirements/related_files/${id}`, { method: 'DELETE', credentials: 'include', headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', Authorization: `Token ${token}`, }, views.py class CommentsView(GenericAPIView): authentication_classes = (TokenAuthentication,) serializer_class = CommentsSerializer def post(self, request): request.data['user'] = request.user.id comment = CommentsSerializer(data=request.data) if comment.is_valid(): comment.save() return Response(comment.data, status=status.HTTP_201_CREATED) return Response(comment.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self,request): ???? what do I do here ???? -
Trying to write a custom template tag in Django that finds a phone number in text and converts it to a link
I want to convert this string tel:123-456-7890.1234 to a a link in html. The final output would be <a href="tel:1234567890,1234">123-456-7890 ext 1234</a> I'm not great with Regex and I'm REALLY close, but I need some help. I know that I'm not all the way there with the regex and output. How do I change what I have to make it work? import re @register.filter(name='phonify') @stringfilter def phonify(val): """ Pass the string 'tel:1234' to the filter and the right tel link is returned. """ # find every instance of 'tel' and then get the number after it for tel in re.findall(r'tel:(\d{3}\D{0,3}\d{3}\D{0,3}\d{4})\D*(\d*)', val): # format the tag for each instance of tel tag = '<a href="tel:{}">{}</a>'.format(tel, tel) # replace the tel instance with the new formatted html val = val.replace('tel:{}'.format(tel), tag) # return the new output to the template context return val I added the wagtail tag as I've seen other solutions for this in Wagtail and is something needed for Wagtail, so this might be helpful to others. -
Serializing a model as Json in Django and parse it with JavaScripts JSON.parse
I am afraid I don’t understand what "serializing" means. If someone can explain I’d be grateful. I am serializing a Django model in Json as explained in the Django Docs: data = serializers.serialize("json", MyModel.objects.all()) In my HTML/JS I access the data as recommended: {{ data|json_script:"data" }} var myData = JSON.parse([document.getElementById('data').textContent]); But instead of being an Object myData is a string. So I guess somehow I serialize twice or something. I found a solution, JSON.parse works as expected on my data now: data = json.loads(serializers.serialize("json", CoursePage.objects.child_of(self).live().public())) But I guess I still don’t understand the meaning of "serializing" properly. The Python docs say about json.loads(s): "Deserialize s (a str instance containing a JSON document). Why do I have to deserialize before JSON.parse works? The description for JSON.parse states: "The JSON.parse() method parses a JSON string"? Which I thought Djangos serializer would gave me in the first place. I am confused. -
Django bulk create and primary keys
So I have a model in my Django app (Unit, many to one to Property relationship) that is added in bulk via UI. The numbers of instances added could vary between 1 and 1000+ (but usually not much higher than that). Adding it in a loop using the model save() method seems inefficient (over a thousand separate db queries). So I learned about the bulk_create() method, but then learned that it doesn't populate the primary key field (AUTOFIELDS). So being new to Django, here are some options I can think of to implement this: Just bite the bullet and do it the slow way, using Model save(). Do bulk_create() to add these without a primary key, and just manage them in the app by their other fields (unit name, property). Implement a complex bulk_create method generating my own pks and using db locking. Approximate pseudocode below: break the list of units to create into digestible blocks for each block lock the unit table using SQL (to prevent pk from changing) get the current max pk of the table use an iterator to assign pks to unit instances use bulk_create to insert all the intances into db with assigned pks unlock … -
How to get an input value from template (datetimepicker input) and use it into the views.py in a function view
Hello guys I am startin with Django and I have a question about filter data. I want to export data from a model using import_export module with a button in the template ( no form in the template is in the listview template) : <a class="dropdown-item" href="{% url 'cmp:export' %}" role="button">Exportar Proveedores</a>` datepicker input: <div class="input-group date" data-target-input="nearest"> <input type="text" id="{{fecha_exportacion}}" name="fecha_exportar" class="form-control datetimepicker-input datepicker" data- target="#datetimepicker"/> <div class="input-group-append" data-target="#datetimepicker1" data- toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i> </div> </div> urls.py: path('proveedor_export',export,name='export') views.py def export(request): **date = request.GET.get('fecha_exportar')** user_selected_date = datetime.strptime(date, '%Y %m, %d') proveedor_resource = ProveedorResource() queryset = Proveedor.objects.filter(fc=user_selected_date) dataset = proveedor_resource.export(queryset) response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="proveedores.csv"' return response But I do not know how retrieve the datepicker input value and pass it to the views for the variable date. I tried with request.GET.get('fecha_exportar') but the result is None. -
Django/Python/MongoDB: How to update part of the web page/form
I have successfully coded and launched an internal site with Python+Django+MongoDB backend. Works great! But I would like to improve the user experience. There is a form where I pull up some data from MongoDB (by aggregation, counting etc.) and show it on a table (Table1). Now if a user clicks on a particular count on a table row I would like to send another HTTP request to add a section in the same page with more information (Table2). Currently I am sending query with extra parameter to the same "form" element which does bring the "more information" for that table row and create the Table2 but it also sends the same MongoDB query to re-create the first table (Table1) (basically rendering the whole page). This part I want to avoid... I do not want to re-do the first query and would like to fill only Table2 part of the webpage. I know it can be done in Angular - I worked very briefly with Angular where I was calling REST API to connect to MSSQL server and that brings the JSON result payload and then I was using Javascript/Angular to fill certain parts of the website as needed without …