Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Forms.py Email And Phone Validation
I have a contact form created with forms.py that I would like to add validation with regular expressions or any built in Django validators for the email and phone fields. The only files I am using are forms.py, views.py, and the html template (there is no models.py for this contact form). If the user enters an incorrect phone number or email, I want to show them a message saying their format is incorrect and that they need to correct their input. The form should not be able to be submitted until the user enters valid data. What I have tried below: Forms.py: https://dpaste.org/mc7G Views.py: https://dpaste.org/0PFZ Html template: https://dpaste.org/bBvR How would I do this using Django only and without JavaScript? -
Handling a recommendation system in python - Django
So I'm trying to build a simple system that would display the products as a slider in the homepage that a user already visited in the past but I'm not sure how to do it. For example, let's say that I've been using a search engine to find shaving tools for men. Now getting some results back, I click on the product image which then redirect me to the actual product page (/product/razor-for-men-1038/), I end up visiting a couple of pages and nothing really fits my actual needs so I decide to close all of them. A week later, I return on the same website with the intention of ordering one of the products I've seen in the past. I type the exact same query but none of these products show up which pisses me up real bad and I end up not ordering from this website. Story aside, would it be possible to know the pages they last visited and based on that, displaying the content of the products (image & title) directly from the homepage in a tailored section? I'm really unsure on how to handle that so I'm open to any suggestions (Using Cookies, Javascript, Python-Django, softwares, … -
File : "Upload a valid image" using Postman in Django Rest Framework
I am using Django Rest Framework to upload profile picture and Google Cloud Storage to store my images. I test my API with Postman and i have this result : Postman result And here is my Postman headers : Postman headers This is my code : class ProfilePictureSerializer(serializers.Serializer): file = serializers.ImageField() class UploadProfilePictureAPI(APIView): permission_classes = (IsAuthenticated,) parser_classes = [FileUploadParser] @staticmethod def post(request): input_serializer = serializers.ProfilePictureSerializer( data=request.data ) input_serializer.is_valid(raise_exception=True) profile = ProfileService.upload_profile_picture( request.user, **input_serializer.validated_data ) output_serializer = serializers.ProfileSerializer(profile) return Response( output_serializer.data, status=status.HTTP_202_ACCEPTED ) @staticmethod def upload_profile_picture(user, file): user.profile.profile_picture = file user.profile.save() return user.profile path( 'upload/picture', views.UploadProfilePictureAPI.as_view(), name='api_upload_profile_picture' ), I does not understand why I have this response. Could you help me ? -
Unsupported media type "multipart/form-data; boundary=----WebKitFormBoundaryABC" when requesting to Django server
I'm uploading a set of data (file, string, number, bool) to an Django api. The docs says Note: the schema is not json it's multipart so I made use of formData which is multipart. But when I upload this form I get this error "Unsupported media type "multipart/form-data; boundary=----WebKitFormBoundaryABC" in request" so I tried to add the content type multipart httpheader but this also resulted in an error: unsupported mediative "multipart" in request I actually don't know where the error lies. Either in the api or in my front end code, so I'll add the essential parts of both down here: Django: models.py class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts', on_delete=models.CASCADE) src = models.ImageField(blank=False, null=False, editable=False, upload_to=utils.get_file_path,) date_posted = models.DateTimeField(auto_now_add=True, editable=False) last_modified = models.DateTimeField(auto_now=True) when = models.FloatField(blank=True, null=True) lock = models.BooleanField(default=False) des = models.CharField( max_length=100, validators=[ RegexValidator( regex='^[-_a-zA-Z0-9\.]+$', message='only 1 to 20 characters and only letters, numbers, point, minus and underscore are allowed', ), ]) frontend upload.ts ngOnInit() { this.categoryForm = new FormGroup({ 'lock': new FormControl(true), 'des': new FormControl('', Validators.compose([ Validators.maxLength(25), Validators.minLength(1), Validators.required ])), 'image': new FormControl(null), 'when': new FormControl(null), }); } apiSubmit() { const formData = new FormData(); formData.append('lock', this.categoryForm.get('lock').value); formData.append('des', this.categoryForm.get('des').value); formData.append('image', this.categoryForm.get('image').value); formData.append('when', this.categoryForm.get('when').value); this.http.post<any>(`{this.url}`, formData).subscribe( (res) => … -
Annotate a `selected_related`'d object in Django
I am building a queryset of a model, and want to put an annotation on a related model that I am selected_related'ing into the queryset. Hypothetically: class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) class Author(models.Model): name = models.TextField() I am selecting Book.objects.all().select_related(), and want to annotate the authors with awesome=True. I could resolve the queryset and alter the objects myself, but is there a cleaner ORM-oriented way to do it? Inverting the operation to select the Authors instead is undesirable. -
NoReverseMatch at /availability/1/edit/ Reverse for 'availability_list' with no arguments not found. Tried: ['availability\\/(?P<pk>[0-9]+)\\/list$']
I'm getting this error using Django 3 when trying to either 1) create a new object (CreateView), or 2) edit an existing one (UpdateView). Using CBVs and ModelForms. I explored similar questions on Stackoverflow. Very often, it's about the template missing pk reference, but I triple-checked that and it doesn't seem to be the case. Any idea? Here are my codes: URLs path('availability/<int:pk>/list', views.AvailabilityListView.as_view(), name='availability_list'), path('availability/new/', views.AvailabilityCreateView.as_view(), name='availability_new'), path('availability/<int:pk>/edit/', views.AvailabilityUpdateView.as_view(), name='availability_edit'), Views class AvailabilityUpdateView(UpdateView): template_name = 'crm/availability_form.html' form_class = AvailabilityForm model = Availability class AvailabilityUpdateView(UpdateView): template_name = 'crm/availability_form.html' form_class = AvailabilityForm model = Availability Forms class AvailabilityForm(forms.ModelForm): class Meta(): model = Availability exclude = [] Models class Availability(models.Model): staff = models.ForeignKey(Staff, on_delete=models.CASCADE) start = models.DateTimeField() end = models.DateTimeField() class Meta: verbose_name_plural = "Availabilities" def get_absolute_url(self): return reverse('staff_list') Template {% block body_block %} <div class="container"> <div class="heading"> <h1>Availability</h1> <a class = 'btn btn-primary' href="{% url 'availability_new' %}">+Create new availability</a> </div> <hr/> {% if availabilities %} <table class="table"> <tbody> {% for availability in availabilities %} <tr> <td>{{availability.pk}}</td> <td>{{availability.staff}}</td> <td>{{availability.start}}</td> <td>{{availability.end}}</td> <td> <a href="{% url 'availability_edit' pk=availability.pk %}">Edit</a> </td> </tr> {% endfor %} </tbody> </table> {% else %} <p class='empty'>Staff does not have any availability</p> {% endif %} </div> {% endblock %} -
Django REST - grab paramater value when part of the URL
I have the following urls.py: from django.urls import path, include from rest_framework.routers import DefaultRouter from location import views router = DefaultRouter() router.register('city', views.CityViewSet, 'city') app_name = 'location' urlpatterns = [ path('', include(router.urls)), ] when hitting the url /api/location/city/25/ I get all the details for that object instance (with the id of 25) as expected. My question how do I grab the id number in my viewset? I know how to do it with just regular query parameters /?id=25, but can't seem to figure out how to do it when it's part of the URL. -
Cannot access cookies after redirect in django
Here is situation I've dealt with. I will try to explain as much as easier to understand. I want user to click on a button in the website (let's name this site A) which fires an ajax post request to django view. Within this view I have response.set_cookie to set cookie with data that is passed along with ajax post request. After success response, then I quickly redirect page to different website (let say this site is B). When page loads, I want to access cookies what I've set from site A but cannot access. Below is my code. index.html (in site A, where the ajax post request is made) <!DOCTYPE html> <html> <head> </head> <body> <button onclick=setCookies()>Create Invoice</button> </body> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script type="text/javascript"> const setCookies = () => { ...some codes... const xhr = new XMLHttpRequest() const data = { 'HTTP_LOGIN_TYPE': 'admin', } $.ajax( { type: 'POST', url: url, // hits endpoint where sets cookies. crossDomain: true, data: data, success: () => { window.location.href = to site B }, error: xhr => { console.log(xhr.responseText) } } ) } </script> </html> views.py (in site B, where sets the cookies) from django.http import HttpResponse from django.conf import settings from … -
How to implement TUS uploading into existing Django project using django-tus and tuspy?
I am looking to implement TUS uploading into a Django project I already have created. I want to use django-tus server-side (https://django-tus.readthedocs.io/en/latest/readme.html) and tus-py client-side (https://tus-py-client.readthedocs.io/en/latest/). My issues are coming up in a couple different places. I have already installed both packages. I imported django-tus into my project and configured the urls: project settings.py INSTALLED_APPS = [ 'django_tus', ] project urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static import django_tus from pages.views import ( home_view, redirect_view, ) from django_tus.views import ( TusUpload, ) urlpatterns = [ path('', home_view, name='home'), path('home/', redirect_view), path('admin/', admin.site.urls), path('products/', include('products.urls')), path('upload/', include('django_tus.urls')), ] django_tus urls.py import django_tus from django.urls import path from django_tus.views import ( TusUpload, ) app_name = 'upload' urlpatterns = [ path('', TusUpload.as_view(), name='tus_upload'), path('<int:id>/', TusUpload.as_view(), name='tus_upload_chunks'), ] Everything else is pretty standard for a basic Django project. Here are the tus views if they're any help: django_tus views.py import os import uuid import logging from django.http import HttpResponse from django.conf import settings import base64 from django.views.generic import View from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from django.core.cache import cache from django.conf import settings from django.urls import reverse from django_tus.signals import tus_upload_finished_signal … -
How to serialize multiple files in Django
I am trying to serialize multiple files, send the files using 'Postman' and have tried several ways to save several files at once. This is the model: class PrtFiles(models.Model): file_name = models.FileField(null=True, blank=True) And I getting this request in my view in Django: <MultiValueDict: {'file_name[0]': [<InMemoryUploadedFile: Inventario Personal_Users [SHORT].xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>], 'file_name[1]': [<InMemoryUploadedFile: Planilla_de_Usuarios_MEL [NEW][SHORT].xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>]}> Whit this Request in Postman: enter image description here Any method that to do that? P.S. I'm beginner with Django, thanks beforehand. -
Heroku config variables doesn't work on django
i want to define some variable for to use settings.py Firstly, i did define variables on heroku web site like this photo. And than, i did call secret_key like this; local_key = "something.." SECRET_KEY = os.environ.get('SECRET_KEY', local_key) But, secret_key is empty. How to fix them? what is my wrong? -
Getting the last for loop iteration of condition in django templates
I wish to add the class rounded-t-lg shadowon the first iteration inside the if statement, and rounded-b-lg shadow on the last iteration. I have the following code: {% for note in notes %} {% if note.is_sticky %} <div class="flex items-center"> <div class="{% if forloop.first %} rounded-t-lg shadow {% elif forloop.last %} rounded-b-lg shadow {% endif %}"> <!-- code --> </div> </div> </div> {% endif %} {% endfor %} The problem that I'm running into is that forloop.last applies to the last iteration in general, and not the last iteration in the condition. So if I have three objects, where two is sticky, and the last one is not, the class will be applied to the one that is not, since its the last in "line". How can I apply a class to the last iteration within the is_sticky condition, regardless of the objects that do not meet the condition? -
403 error when receiving Google Calendar API notification
I have calendar events being created successfully for various GSuite users, then I'd like to set a watch event. I'm able to do that successfully: SCOPES = ['https://www.googleapis.com/auth/calendar'] SERVICE_ACCOUNT_FILE = BASE_DIR + 'path_to_json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) delegated_user = credentials.with_subject(user) delegated_service = googleapiclient.discovery.build('calendar', 'v3', credentials=delegated_user) event = { 'summary': '%s at %s' % (event_name, event_location), 'description': 'description', 'location': event_address, 'extendedProperties': { "private": { 'briefType': event_name, } }, 'start': { 'dateTime': event_start_time.astimezone().isoformat(), }, 'end': { 'dateTime': event_end_time.astimezone().isoformat(), } } event = delegated_service.events().insert(calendarId='primary', body=event).execute() watch_body = { 'id': event['id'], 'type': 'web_hook', 'address': 'https://example.com/googleapi' } watch = delegated_service.events().watch(calendarId='primary', body=watch_body).execute() I'm not quite sure how to receive the push notification. I've registered/added my domain (per https://developers.google.com/calendar/v3/push), and when I change the event in Google Calendar I'm getting an API Push notification, but I'm receiving a 403 error: Dec 11 20:58:38 ip-xxx gunicorn[3104]: - - [11/Dec/2019:20:58:38 +0000] "POST /googleapi HTTP/1.0" 403 1889 "-" "APIs-Google; (+https://developers.google.com/webmasters/APIs-Google.html)" How do I authenticate in the view that process /googleapi to be able to actually receive the API notification from Google? I've tried the following just to try to debug what I'm receiving from Google, but I get nothing besides the 403 error: def GoogleAPIWatchView(request): SCOPES = ['https://www.googleapis.com/auth/calendar'] SERVICE_ACCOUNT_FILE … -
Django can't override form field widget
guys. I need to generate column based checkboxes in my form. # myapp/templates/forms/widgets/custom.html <div class="row"> {% for group, options, index in widget.optgroups %} {% for option in options %} <div class="col-md-3"> {% include option.template_name with widget=option %} </div> {% endfor %} {% endfor %} </div> and here is my form # myapp/forms.py class CustomCheckboxSelectMultiple(forms.CheckboxSelectMultiple): template_name = 'forms/widgets/custom.html' class HomePageContactForm(forms.Form): ... other fields ... services = forms.ModelMultipleChoiceField( queryset=Service.objects.all(), widget=CustomCheckboxSelectMultiple(), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_show_labels = False I added 'django.forms' in my INSTALLED_APPS list, but forms render default CheckboxSelectMultiple template. Also I tried to put this template to myapp/templates/django/forms/widgets/checkbox_select.html, but had no luck, render default template again. For debugging I set template_name='template_which_not_exist', but still got no errors and render default template. Please help me -
Python:Find Nearby mobile devices
I want to create software using python,find all that mobile devices which available nearby.they give me all information about mobile device like,distance,model number etc. -
Empty request.POST on Django AJAX call
I am trying to send form data to one of my view. But I am getting empty request.POST My ajax call is : ajaxSubmit = () =>{ exam_type = document.getElementById('exam_type').value total_marks = document.getElementById('total_marks').value var request = new XMLHttpRequest(); request.open('POST', "{% url 'addExamForm' %}", true); request.setRequestHeader("X-CSRFToken", "{{ csrf_token }}") request.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); request.onload = function() { if (this.status >= 200 && this.status < 400) { alert("Success"); } else { alert("Fail"); } }; request.send(JSON.stringify({"exam_type":exam_type,"total_marks":total_marks})); } -
Using domain name for Django application deployed on DigitalOcean
I've created a django application, deployed it on DigitalOcean, and everything works and looks well when using website via IP address. Now I've bought a domain and want to use it for my application, but don't know what to do. First of all I've added my domain name to ALLOWED_HOSTS in settings.py, then DigitalOcean's DNS servers added to site where I bought domain. But app doesn't work via domain name yet. Here are my codes: settings.py: ALLOWED_HOSTS = ['64.225.1.249', 'forexample.az'] nginx: /etc/nginx/sites-available/myproject server { listen 80; server_name my_ip_address (not domain, maybe here I should write domain name ?); location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/my/_username//myproject; } location / { include proxy_params; proxy_pass http://unix:/home/my/_username/myproject.sock; } } -
Can't use Python dict in Django template tag
I checked multiple posts and solutions but can't make it happen. I have a Python object returned within a view. I now want to use data from that dict to render it using Django template tags. Somehow nothing shows up though... View: def render_Terminal(request, template="Terminal.html"): account_information = AccountInformation.objects.all() account_information_dict = { 'account_information': account_information } return render(request, template, (account_information_dict)) HTML <div id="oneTwo" class="columnsOne"> {{ account_information.pk }} </div> Using just account_information within the tag, I get: <QuerySet [<AccountInformation: AccountInformation object (30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f)>]> Where is the issue? -
Django - Ajax or not Ajax?
I have a Django project with a classical navabar which contain a select and other link with dropdownmenu I have a function that query the database to control drug stocks in a center (user's center - CHU by default - or center selected) and return a bool if true, the red alert 'Insufficient stock' is display and link 'Randomize a patient' and 'Reallocate a patient' should not be display I would like drug stock to be reevaluated when user select another center without reloading the page I think I should use ajax but I am lost on how to implement -
Django Error on django-admin startproject
i try this command: $ virtualenv .venv $ sourse .venv/bin/activate (.venv) $ pip3 install django The last command installed the django3 on the whole system while the virtual machine was active and should only be installed on the virtual machine. why?? i tried django-admin stratproject mysite, but i received this error: Command 'django-admin' not found, but can be installed with: sudo apt install python-django-common so, i try sudo apt install python-django-common. then again try django-admin stratproject mysite and resived error: Cannot find installed version of python-django or python3-django. how i can solve this problem?? -
Creating a Django App with FileField Upload and TextField Insertion?
I'm making a form that allows the user to upload their PDF and add a text input. So far, the file upload functionality works, but whenever I add the text insertion functionality, the project goes haywire. I was wondering how this text insertion can be saved and whether or not my current set-up is correct. I've also included the error that I'm getting when I try to save the TextField and FileField for a model in one view. Any help is greatly appreciated, thank you! My error AttributeError at / 'Resume' object has no attribute '_committed' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.0 Exception Type: AttributeError Exception Value: 'Resume' object has no attribute '_committed' models.py from __future__ import unicode_literals from django.db import models from django import forms from django.forms import ClearableFileInput # Enabling the ability to delete files from django.db.models.signals import post_delete from django.dispatch import receiver class Resume(models.Model): # Allow user to upload a PDF resume resume = models.FileField('Upload Resume', upload_to='media/') # Define an industry speification with bound max length of 50 chars industry = models.CharField(max_length = 50, blank = False, null = False) def __str__(self): return self.industry # Possible error here, need to fix! def delete(self, *args, … -
Cannot update chart.js dataset from textbox value
I'm trying to update a column on a bar chart I generate from chart.js using data passed as JSON from a django function. I'm getting the data and I'm able to display the graph but when I want to change the value of one of the bars (by entering a value in a textbox), i get the error: Uncaught TypeError: Cannot read property 'datasets' of undefined at updateChart ((index):70) at HTMLInputElement.onkeyup ((index):90) I'm using AJAX to get the data populate the initial graph and I have a function updateChart() to update the chart with onkeyup(): updateChart() function function updateChart(){ var val = document.getElementById("txt").value; var tmp_chart = document.getElementById("myChart").getContext('2d'); console.log(tmp_chart.data.datasets[0].data[0]); tmp_chart.data.datasets[0].data[0]=val tmp_chart.update() } My whole code is: {% csrf_token %} <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <!-- jQuery 3.4.1--> <script type = "text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script> <script> $.ajax({ method: "GET", url: '/graph/', contentType: "application/json; charset=utf-8", success: function(cia_data){ str_json =JSON.parse("{{cia_data}}".replace(/&quot;/g,'"')); //remove &quote; from json str var lbl = [] for (i=0;i<str_json.length;i++){ lbl.push(str_json[i].CIA_YR) } labels = lbl var data = [] for (i=0;i<str_json.length;i++){ data.push(str_json[i].VALUE) } defaultData = data setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }); function setChart(){ var ctx = document.getElementById("myChart"); ctx.width = 300; ctx.height = 400; var myChart = new Chart(ctx, { // The type of chart we … -
AttributeError: 'ModelSelect' object has no attribute 'annotate'
Open an interactive python shell in this frame@app.route('/profile/') def user_profile(): products = models.Product.select(models.BuyHistory, models.Product).join(models.BuyHistory).annotate(models.BuyHistory, models.BuyHistory.product_quantity).where(models.BuyHistory.buyer == current_user.id) return render_template('user-profile.html', user=current_user, products=products) # cancel order @app.route('/order/cancel/<id>')``` -
Django - get() returned more than one
I have this view bellow and I need to verify my usuario and vaga at the same time. something like if I already have a vaga 1 and usuario X in my db the view jump the form.save...How can i do this? I was trying use VagaUsuario.objects.get(usuario=request.user) and VagaUsuario.objects.get(vaga=item) and i get this error get() returned more than one VagaUsuario -- it returned 2! def vaga_item(request, nr_item): item = get_object_or_404(Vaga, pk=nr_item) form = ListaVagasItem(request.POST or None, request.FILES or None, instance=item) if request.method == 'GET': formsetadd = VagaUsuarioFormset(request.GET or None, prefix='cadastros') elif request.method == 'POST': formsetadd = VagaUsuarioFormset(request.POST, request.FILES, prefix='cadastros') if formsetadd.is_valid(): try: VagaUsuario.objects.get(usuario=request.user) and VagaUsuario.objects.get(vaga=item) messages.error(request, 'Vaga já cadastrada. Selecione outra!', extra_tags='alert') return redirect("vagas") except VagaUsuario.DoesNotExist: for form in formsetadd: vaga = item status = True if vaga and status: VagaUsuario( vaga=vaga, status=status, usuario=request.user ).save() messages.success(request, 'Vaga cadastrada com sucesso!', extra_tags='alert') return redirect("vagas") return render(request, "personal/item.html", { 'form': form, 'formsetadd': formsetadd }) -
How to let my computer know I want to use python 3 now?
I have a mac and python 2.something installed. I recently installed python3 and pip3. Then I tried running the following commands: pip3 install django==2.2 django-admin startproject myProject cd myProject everything worked, but when I run python3 manage.py runserver it complains Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? is my computer still thinking in the old version? I am not familiar with "environment variables" do I need to modify it? (I am asking cause I also read that it can be unsafe to modify that stuff) Also, when I run python --version it gives me 2.7