Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Password-Protect Django Delete View
I have a basic DeleteView for the user model, which essentially provides the user with the ability to delete their account. The user delete view looks like this: class UserDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = User template_name = 'User/user_confirm_delete.html' def get_success_url(self): messages.add_message(self.request, messages.INFO, 'You no longer exist.') return reverse_lazy('blog-home') # check if current user is the user being deleted def test_func(self): return self.request.user == self.get_object() and the confirmation form in the template (user_confirm_delete.html): <form method="post">{% csrf_token %} <div class="dual-option-container"> <button class="danger button" type="submit">Delete</button> <a href="{% url 'user-profile' %}" class="button">Cancel</a> </div> </form> I want to have the user enter their password as confirmation before they delete their account. How would I go about doing this? -
How to make a image gallery like of spotify
I want to create a image gallery like of spotify's. For my project's backend I am using django and all that stuff is done. But I don't have any idea like how would I create a image gallery like this? What I want is there will be collage for the whole thing and after I click one of it I can see each picture individually exactly what spotify has done. I can't think of how the frontend should be. Any ideas about how can I do it will be extremely helpful. Thank you very much. -
Django - Relationships in Model. One To One, One To Many, Many to Many. please explain with example
Anyone explains one to one, one to many, many to many relations with example in Django. -
Django - strptime() argument 1 must be str, not None
In my application user is entering his name, email, meeting date and meeting hour and I want to save all these information to my database. But application is not running. I'm getting TypeError: strptime() argument 1 must be str, not None but don't what is the reason. Everything seems like true. models.py: def index(request): context = { 'schedules': Schedule.objects.all() } participant_name = request.POST.get('name') participant_email = request.POST.get('email') meeting_date = request.POST.get('date') meeting_hour = request.POST.get('hour') converted_meeting_date = datetime.strptime(request.POST.get('date'), "%m-%d-%Y") converted_meeting_hour = datetime.strptime(request.POST.get('hour'), "%H:%M") if request.POST.get('participant_email'): Schedule.objects.create( participant_name = request.POST.get('name'), participant_email = request.POST.get('email'), meeting_date = converted_meeting_date, meeting_hour = converted_meeting_hour ) return render(request, 'index.html', context) models.py: class Schedule(models.Model): participant_name = models.CharField(max_length=100) participant_email = models.CharField(max_length=100) meeting_date = models.DateField() meeting_hour = models.TimeField() is_scheduled = models.BooleanField(default=False) def __str__(self): return self.participant_name -
Save file path depending on contents of uploaded file in Django REST Framework
I am trying to save an uploaded file to a specific path, depending on its contents. The file is uploaded to a Django REST Framework API in Base64 format inside a JSON object. The file, if valid, contains a unique id for the Machine model that I want to store in the database and use as part of the path in which this and other relevant files will be saved. The UniqueIDAndInfo file needs to be saved because it doesn't only contain the ID I am talking about. It should be very easy to extract the ID, save it as a field in the model instance, and then tell the Storage system to save the file in a specific directory according to the ID value. I am getting the file using the drf_base64 extension in the following, simple way: class MachineSerializer(serializers.ModelSerializer): class UniqueIDAndInfoBase64File(drf_base64.Base64FileField): pass unique_id_and_info = UniqueIDAndInfoBase64File(allow_null=False, allow_empty_file=False) What I am trying to accomplish is something like this, if the upload_to callback accepted the contents of the file as an argument: def content_file_name(instance, filename, file_contents): # file_contents is not a true argument of this function! unique_id = process_unique_id_and_info_file(file_contents) return os.path.join(MACHINE_FILE_FOLDER, unique_id, 'unique_id_and_info.info') class Machine(models.Model): unique_id_and_info = models.FileField(upload_to=content_file_name) -
Creating A Form From A Forerign Key In Django
Is there a way I can create a form in Django with inclusive of a foreign key which also should be created as the form is filled and not selected? -
Django: Join ManyToManyField with CharField in Frontend
I need to register which passengers are on my ride. Therefor I use the following classed: class Member(models.Model): name = models.CharField(max_length=32) ... class Ride(models.Model): passengers = models.ManyToManyField(Member) ... That way it is easy to select the passengers which are members in the ride. So far so good. But I want to add passengers (just by their name) which are not members as well (without adding new member instances). My guess is to write a custom widget: A comma separated list with an autocomplete for existing members (Select2). Something like the address bar in an email-app. Does anyone know a ready-to-use solution? -
Django admin: How to show calculated value from entered values dynamically in Django admin form page?
I have a form which is having a 'price', 'tax' and 'discount' fields (IntegerFields). And then one more read-only field will be there called 'total_price'. while we enter the 'price', 'discount' and 'tax', automatically 'total_price' value should display. If we change the 'discount' or 'price' then 'total_price' also change immediately. After seeing the final price, we can click the 'Save' button. How to attain this in Django admin? -
How to remove table not found error in django?
I am creating an API in django where i'm trying to make post request through json file and it is throwing error no such table: main.restapi_quiz__old" But there are no such table and i have tried removing all migrations and re-creating it but it's still showing this error. My Model: class QuizCat(models.Model): category_name = models.CharField(max_length=200) class Quiz(models.Model): category_id = models.ForeignKey(QuizCat, on_delete=models.CASCADE) name = models.CharField(max_length=200) class UserDetails(models.Model): user_id = models.IntegerField() Qid = models.ForeignKey(Quiz, on_delete=models.CASCADE) score = models.IntegerField() Why am i getting this error and how can i remove it ? -
Usage of RabbitMQ queues with Django
I'm trying to add some real-time features to my Django applications, for that i'm using RabbitMQ and Celery on my django project, so what i would like to do is this: i have an external Python script which sends data to RabbitMQ > from RabbitMQ it should be retrieved from the Django app. I'm sending some muppet data, like this: connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='Test') channel.basic_publish(exchange='', routing_key='Test', body='Hello world!') print(" [x] Sent 'Hello World!'") connection.close() What i would like to do is: as soon as i send Hello World!, my Django app should receive the string, so that i can perform some operations with it, such as saving it on my database, passing it to an HTML template or simply printing it to my console. My actual problem is that i still have no idea how to do this. I added Celery to my Django project but i don't know how to connect to RabbitMQ and receive the message. Would i have to do it with Django Channels? Is there some tutorial on this? I found various material about using RabbitMQ and Celery with Django but nothing on this particular matter. -
Django with UDP socket - What should I use, Twisted Plugin or Django Channels?
I'm making the Django website and need parsing some data from the UDP socket. I found https://twistedmatrix.com/documents/current/core/howto/tap.html , what can help me handle UDP socket very easy, when I embed it to Django project, it doesn't run. how to embed it to Django? -
Django views: postgres materialized view accessible via get but not via filter (both queryset)
I try to filter materialized postgres views in Django views.py. The database and the views were created with postgres. I can filter views which represent one to many relationships and I can access views with get (queryset) which represent many to many relationships. But I cannot filter those views which represent many to many relationships. Models were created with inspectdb. It's a postgis legacy database. How do I have to filter these views? models.py fid = models.AutoField(primary_key=True) id_dokument = models.IntegerField(blank=True, null=True) dokument = models.CharField(max_length=50, blank=True, null=True) datei = models.CharField(max_length=100, blank=True, null=True) beschreibung = models.CharField(max_length=1024, blank=True, null=True) datum = models.DateField(blank=True, null=True) person = models.CharField(max_length=50, blank=True, null=True) dokumenttyp = models.CharField(max_length=30, blank=True, null=True) id_objekt = models.IntegerField(blank=True, null=True) objekt = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False # Created from a view. Don't remove. db_table = 'objekt_dokumente_rel' views.py dokumente = ObjektDokumenteRel.objects.using('db').filter(id_objekt=fid) If replacing filter with get I receive one object (as expected). -
How to connect a django app to bokeh server?
I'm currently trying out bokeh server to serve some interactive bokeh charts to my django app, but having difficulty connecting via views.py. The browser returns an OSError: Cannot pull session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command) The server itself returns 404 error for the request: 200-03-31 08:17:09,179 404 GET /ws?bokeh-protocol-version=1.0&bokeh-session-id=ZhGn4XcmC1qDPYtF4SRPGPa1GzSgTqktqmvkIEGJke26 (127.0.0.1) 0.55ms My server is set up as follows: bokeh_server | |--main.py main.py is a very basic bokeh chart main.py from bokeh.io import curdoc from bokeh.layouts import column from bokeh.plotting import figure from bokeh.models.sources import ColumnDataSource source = ColumnDataSource(dict(x=list(range(5)), y=list(range(5)))) p = figure(width=300, height=300, tools=[], toolbar_location=None, name="test") p.line(x='x', y='y', source=source) curdoc().add_root(column(p, sizing_mode='scale_width')) Running the server (bokeh serve bokeh_server) and then opening https://localhost:5006 in a browser renders the chart correctly (https://localhost:5006/bokeh_server) The issue comes when I try to open it from my django app. views.py from django.shortcuts import render from django.http import HttpResponse from bokeh.client import pull_session def testbserver(request): session = pull_session(url="http://localhost:5006/") script = server_session(model=None, session_id=None, url="http://localhost:5006/", ) return render(request, 'testserver.html', {'script':script}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('testbserver/', views.testbserver, name='testbserver'), ] testserver.html {% extends "base_generic.html" %} {% block content … -
ModuleNotFoundError: No module named 'To_do.todos' - DJANGO
So I just started learning django, and I was learning from this youtube video: https://www.youtube.com/watch?v=Nnoxz9JGdLU So here is my directory map: To_do +To_do +_pycache_ +_init_.py +asgi.py +settings.py +urls.py +wsgi.py +todos +_pycache_ +migrations +_init_.py +admin.py +apps.py +models.py +tests.py +urls.py +views.py +db.sqlite3 +manage.py code of To_do/To_do/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('todos/', include('todos.urls')) ] code of To_do/todos/urls.py from django.urls import path from . import views urlpatterns =[ path('list/',views.list_todo_items) ] code of To_do/todos/view.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def list_todo_items(request): return HttpResponse('from list_todo_items') My Issue: After using the above codes with re-directions, clearly i'm messing up somewhere, as in the "main" urls.py file present in the project directory, when I'm running my server i get the error: $ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/smith/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/smith/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/smith/.local/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/home/smith/.local/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/smith/.local/lib/python3.6/site-packages/django/core/checks/registry.py", … -
How to delete record from database by using input form in django
So i have this small web program in which a user can enter his/her email and receives some updates. Nevertheless this email is saved in the database (sqlite3) and i have a form in which a user can unsubscribe, my problem is i'm trying to find a way to take the input from the unsubscribe form & if it matches any record in the database it deletes it. Does anyone have any suggestions? This is the view i'm trying to create but doesn't work def unsubscribe_view(request): form = EmailForm() if request.method == "POST": form = EmailForm(request.POST) value = form.cleaned_data['email'] if form.is_valid(): Email.objects.filter(email = value).delete() context = { 'form' : form, } return render(request, 'Version/unsubscribe.html', context) This is the html page <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <div style="text-align : center;"> <h1> UnSubscribe Page </h1> <div class="container"> <div class="row"> <form method="post" action="/"> {% csrf_token %} {{form}} <button type="submit" class="waves-effect waves-light btn-small">Unsubscribe</button> </form> </div> </div> </div> This is the model if its any helpful from django.db import models # Create your models here. class Email(models.Model): email = models.EmailField() def __str__(self): return self.email This is the form from django import forms from django.forms import ModelForm from .models import … -
List all video files from a usb storage device in Raspberry Pi as soon as the drive is plugged in
It should be similar to that Django Jquery file upload interface as in the link https://blueimp.github.io/jQuery-File-Upload/ except that the files should be listed automatically instead of uploading. I have no idea what to do or how to do it. Therefore I am asking you guys for help! Any help will be appreciated, Thanks, -
Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<book_id>[0-9]+)/$']
I was creating online library, when I had made my 'cart app' I got this error message Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P[0-9]+)/$'] The main page(http://127.0.0.1:8000) is displayed normally As soon as I click the title of the book, that error appears. here is my cart app cord please save me pleas.......T_T from django.conf import settings from library.models import Book class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, book, quantity=1, update_quantity=False): book_id = str(book.id) if book_id not in self.cart: self.cart[book_id] = {'quantity': 0} if update_quantity: self.cart[book_id]['quantity'] = quantity else: self.cart[book.id]['quantity'] += quantity self.save() def remove(self, book): book_id = str(book.id) if book_id in self.cart: del self.cart[book_id] self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def __iter__(self): book_ids = self.cart.keys() books = Book.objects.filter(id__in=book_ids) for book in books: self.cart[str(book.id)]['book'] = book def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def clear(self): self.session[settings.CART_SESSION_ID] = {} self.session.modified = True from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) from django.urls import path from . import views app_name … -
How can I serialize Django REST framework Serializers?
Maybe this isn't possible but given a Django Serializer class like this: class ExampleSerializer(serializers.Serializer): name = serializers.CharField(min_length=1, max_length=200) I'd like there to be a way for the client to get it like a JSON Schema like this (I don't particularly care about the format, OpenAPI would be okay too): { "$id": "https://example.com/example.schema.json", "$schema": "http://json-schema.org/draft-07/schema#", "title": "ExampleSerializer", "type": "object", "properties": { "name": { "type": "string", "minLength": 1, "maxLength": 200 } } } The advantage of this is that I don't have to duplicate the schema logic in the client too. I tried to use their CoreAPI which documents endpoints but it seems like in order to use it I'd need to convert all my serializers to use their AutoSchema format. I don't want to do because I already have it in the seralizer format. What's the recommended way to do this? If there isn't one (already asked on Reddit), it'd be relatively easy for me to create a Serializer-to-JSONSchema converter but I can't imagine I'm the first person to have wanted this. -
how can i add a background image to my website i am using python and django
how can i add a background image to my website? i am very new to programming and can someone pls tell me how can i add a background image i saw a few tutorials and talk about something like css and but i am confused can some pls help me.here is the code i have written please tell me what i can add to add a background image. index.html {% extends 'base.html' %} {% block content %} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ product.image_url }}" alt="..." width ="100%"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.price }}₹</p> <a href="#" class="btn btn-primary">Add to cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %} settings.py """ Django settings for pyshop project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'fe#w(lb3nf8pqg0s0)9ux9r3_#c7v8p$28(qvtoko=l-ffjg8v' # … -
How to show Realtime data in a Django Webpage?
I am using Django to build a Webpage.I need to show my sensor values that is coming from an Esp32 board .which is connected to the same local network and Sends a message through TCP socket every 10 seconds,I need to collect this data and show this in Django Webpage,Could anyone help me with the code snippets to do so? -
Creating a downloadable Link with pk in Django
I've a code view which has a pk (primary key), when I click on the link in HTML, nothing seems to be working... Here's my code for easy understanding Views: ''' import mimetypes From wsgiref.util import Filewrapper def audio_download (request, pk): download =get_object_or_404(Audio,pk=pk) file =download.audio.audio.url.strip('/') wrapper = FileWrapper(open(file, 'rb')) response= HttpResponse(wrapper, content_type='application/force-download') response ['Content-Disposition]="attachment; filename="+os.path.basename(file) Print ('response') return response Then my url: ''' url (r'^audio/download/(P<pk>\d+)/$, views.audio_download, name= 'audio_download') Then lastly, HTML {%for audio in audio%} <a href = "audio/download/{{audio.id}}">{{audio.title}}</a></center> {%endfor%} -
How to render interactive Dash - Plotly using Django (REST framework)?
I'm currently working with generating dashboards. While I understand I can add plotly dash in django templates. I don't seems to understand to use it in a REST framework. I want to know if it is possible to return an 'url' to the front end and on accessing that url - the plotly dash is displayed. Any ideas on how to do this? -
save objects from views to another table drf
i am trying to save data in this table but i'm getting two field only and all the other i want to add manually models.py: class ProviderStatus(UUIDBase): provider_id = models.ForeignKey(Provider, to_field="uid", db_column='provider_id', verbose_name=_("Provider id"),on_delete=models.DO_NOTHING) created_by = models.ForeignKey(User, to_field="uid", db_column='created_by', verbose_name=_("created by"),on_delete=models.DO_NOTHING, null=True) remark = models.TextField(_("Remark"), blank=True, null=True) effective_date_from = models.DateField(_("Effective Date From"),auto_now_add=False,auto_now=False, null=True) effective_date_to = models.DateField(_("Effective Date To"), null=True) provider_status = models.ForeignKey(ProviderStatusChoice, to_field="key", null=True, blank=True, verbose_name=_("Status"), on_delete=models.DO_NOTHING) serializers.py: class ProviderStatusSerilaizer(serializers.ModelSerializer): class Meta: model = ProviderStatus fields= ('uid','provider_id','created_by','remark','effective_date_from','effective_date_to','provider_status') views.py: i have other view and inside that i'm getting output parent_success_obj from that i'm getting its uid and also getting status field and i want to save these fields in this table provider_id = parent_success_obj.uid provider_status = status and other fields i'm taking null or date.now() how should i proceed in views.py: if 'parent_success_obj.uid': serializer_obj = ProviderStatusSerilaizer(data=data) if serializer_obj.is_valid(): serializer_obj.save() else: return CustomeResponse(request=request, comment=FIELDS_NOT_VALID, data=json.dumps(serializer_obj.errors, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) i'm saving this data inside same view -
Django filter date before deadline
I want to filter the date 5 days before the deadline in Django, I already have a query but not working. How can I solve this? django views def bdeadline(request): def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) dl = books.objects.filter(deadline = datetime.now().date() +timedelta(days=5)) return render(request, 'deadline.html',{'title':'Car - Deadline', 'dl':'dl'}) -
Could not able to extend user model using OneToOneField because of migrations not changes
I have model named Voter. I want to authenticate it using django authentication. So I added OneToOneField. I am using this tutorial. but when I add bellow line, applyed makemigrations and migrate and try to fetch Voter objects then it generate error user = models.OneToOneField(User, on_delete=models.CASCADE) Previously I thought that i had done something wrong with extending user. But reading other answers in stackoverflow now it seems that it is because of migration is not applying. Code model.py(partial) class Voter(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # this line map voter with user but it produce error serial_voter_id = models.AutoField(primary_key=True) voter_id = models.CharField(unique=True, max_length=10) voter_name = models.CharField(max_length=255) voter_constituency = models.ForeignKey(Constituency, models.DO_NOTHING, blank=True, null=True) username = models.CharField(unique=True, max_length=32) password = models.TextField() voter_address = models.CharField(max_length=255, blank=True, null=True) area = models.CharField(max_length=10, blank=True, null=True) city = models.CharField(max_length=10, blank=True, null=True) pincode = models.IntegerField(blank=True, null=True) adhar_no = models.BigIntegerField(unique=True) birth_date = models.DateField() age = models.IntegerField() fingerprint = models.TextField(blank=True, null=True) authenticity = models.CharField(max_length=3, blank=True, null=True) wallet_id = models.TextField() class Meta: managed = False db_table = 'voter' migration entry from migrations/0001_initial.py migrations.CreateModel( name='Voter', fields=[ ('serial_voter_id', models.AutoField(primary_key=True, serialize=False)), ('voter_id', models.CharField(max_length=10, unique=True)), ('voter_name', models.CharField(max_length=255)), ('username', models.CharField(max_length=32, unique=True)), ('password', models.TextField()), ('voter_address', models.CharField(blank=True, max_length=255, null=True)), ('area', models.CharField(blank=True, max_length=10, null=True)), ('city', models.CharField(blank=True, max_length=10, null=True)), ('pincode', models.IntegerField(blank=True, …