Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run a subprocess along with Django runserver
I am a novice at Django. I have a simple python script which I execute via a custom command using manage.py, which in turn sets up a subprocess that keeps running. I am using the subprocess to publish message to all channels connected to my server. Right now, the way my code works is that my server runs in one terminal tab while I use a second terminal to run my custom command. My question is, what do I need to do so that whenever I start my server, the subprocess automatically begins in background and keeps on running until server is stopped? I have tried adding the subprocess to ready method of my apps.py, but that does not work. I also tried using channels' background tasks, but that again require executing another command. My custom command handler file from django.core.management.base import BaseCommand from asgiref.sync import async_to_sync import subprocess from channels.layers import get_channel_layer channel_layer = get_channel_layer() class Command(BaseCommand): def handle(self, *args, **kwargs): with subprocess.Popen(['python3', '-u','script.py'],stdout=subprocess.PIPE, bufsize=0, universal_newlines=True) as p: for line in p.stdout: line = str(line.rstrip()) print(line) async_to_sync(channel_layer.group_send)('logwatcher', {'type': 'chat_message','message': line}) p.stdout.flush() Please help me as to what to use and how to use it. Just the link to relevant … -
attempt to write a readonly database
OperationalError at /users/ Request Method: POST Request URL: http://localhost:8000/users/ Django Version: 3.0.3 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: C:\Users\parul\anaconda\envs\MyDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396 Python Executable: C:\Users\parul\anaconda\envs\MyDjangoEnv\python.exe Python Version: 3.8.5 Python Path: ['C:\Users\parul\Desktop\Djangoforms\ProTwo', 'C:\Users\parul\anaconda\envs\MyDjangoEnv\python38.zip', 'C:\Users\parul\anaconda\envs\MyDjangoEnv\DLLs', 'C:\Users\parul\anaconda\envs\MyDjangoEnv\lib', 'C:\Users\parul\anaconda\envs\MyDjangoEnv', 'C:\Users\parul\anaconda\envs\MyDjangoEnv\lib\site-packages'] Server time: Wed, 23 Dec 2020 16:14:46 +0000 Also, i checked the properties in db.sqlite3, all the permissions are checked...write permission also can anyone help using windows... i tried : cacls . /t /e /g everyone:f but still facing the same issue -
I am getting Integrity error in django rest framework
I am begginer in django. I would like to add some posts and comments but I am getting an Integrity error. Without comments model it was working before but it doesn´t work together. I already delete my database and makemigrations and migrate again. post models from django.db import models from django.conf import settings # from django.contrib.auth import get_user_model # User = get_user_model() # Create your models here. class Post(models.Model): user = models.ForeignKey( #to=User, to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts', null=True ) content = models.CharField( max_length=150, blank=False ) created = models.DateTimeField( auto_now=True ) liked_by = models.ManyToManyField( #to=User, to=settings.AUTH_USER_MODEL, related_name='liked_posts', blank=True ) post serializer from rest_framework import serializers from .models import Post from ..comment.serializers import CommentSerializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post comments = CommentSerializer(source='comments.content') fields = [ 'id', 'user', 'content', 'comments', 'created', 'liked_by', ] comment.models from django.db import models from django.conf import settings from apps.post.models import Post # Create your models here. class Comment(models.Model): user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comment', null=True) post = models.ForeignKey(to=Post, on_delete=models.SET_NULL, related_name='comment', null=True) content = models.CharField(max_length=150) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Comment by: {self.user}' comment serializer from rest_framework import serializers from .models import Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['id', 'user', 'post', 'content', 'created'] -
Django filter data using field in another model connected via foreign key
I have two models; Sets and Cards. There are many cards in one set. I would like to get it so that I can filter the cards that are returned in my tables but the set code, which for the example below is khc. I have manage to get it to work to an extent by adding filter(set__code__exact="khc") to the Card.objects but this does not allow the user to change that filtering on the web page. I cannot seem to add a code filter to the CardFilter models.py class Set(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) code = models.CharField(max_length=64) ... class Card(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... set = models.ForeignKey(Set, on_delete=models.CASCADE, related_name='Card') views.py def cards_page(request): card_list = Card.objects.filter(set__code__exact="khc").order_by('name') card_filter = CardFilter(request.GET, queryset=card_list) card_list = card_filter.qs filters.py class SetFilter(django_filters.FilterSet): code = CharFilter(field_name='code', lookup_expr='iexact', label='', widget=TextInput(attrs={'placeholder': 'Set Code', 'class': 'page-input', 'style': 'width: 150px;'})) name = CharFilter(field_name='name', lookup_expr='icontains', label='', widget=TextInput(attrs={'placeholder': 'Name', 'class': 'page-input', 'style': 'width: 150px;'})) type = CharFilter(field_name='type', lookup_expr='icontains', label='', widget=TextInput(attrs={'placeholder': 'Type', 'class': 'page-input', 'style': 'width: 150px;'})) class Meta: model = Set fields = '' class CardFilter(django_filters.FilterSet): # doesnt work # code = CharFilter(field_name='set', lookup_expr='iexact', label='', widget=TextInput(attrs={'placeholder': 'Set Code', 'class': 'page-input', 'style': 'width: 150px;'})) name = CharFilter(field_name='name', lookup_expr='icontains', label='', widget=TextInput(attrs={'placeholder': 'Name', 'class': … -
How to exclude model name and model field names from built-in error message or how translate custom error message in Django/DRF?
I have a User model with email as unique field class User(AbstractBaseUser): ... email = models.EmailField( max_length=50, unique=True, ) ... For serialization I use ModelSerializer: class UserRegisterSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=30, write_only=True ) class Meta: model = User fields = ['email', 'password'] When I attempt to create a new User instance with already taken email, I get such message in response: { "email": [ "user with this email already exists." ] } Seems like everything is ok, except the fact, that when I send request with Accept-Language in headers, I get only partially translated message, like: { "email": [ "email դաշտի այս արժեքով user արդեն գոյություն ունի" ] } As you can see there are untranslated words in message, which are email (model field) and user (model name). The question is : How to customize this message in order to exclude field name and model name and get only for example: { "email": [ "already exists." ] } If someone is going to suggest override UniqueValidator, I tell in advance: already tried that, like: class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email' 'password'] email = serializers.CharField( validators=[UniqueValidator( queryset=Meta.model.objects.all(), message="already exists" )] ) password = serializers.CharField( max_length=30, write_only=True ) … -
Django one-to-many relation: optimize code to reduce number of database queries executed
I have 2 models with a one-to-many relation on a MySQL DB: class Domains(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, unique=True) description = models.TextField(blank=True, null=True) class Kpis(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, unique=True) description = models.TextField(blank=True, null=True) domain_id = models.ForeignKey(Domains, on_delete=models.CASCADE, db_column='domain_id') In order to bring ALL the domains with all their kpis objects, i use this code with a for loop: final_list = [] domains_list = Domains.objects.all() for domain in domains_list: # For each domain, get all related KPIs domain_kpis = domain.kpis_set.values() final_list.append({domain:domains_kpis}) The total number of queries i run is: 1 + the number of total domains i have, which is quite a lot. I'm looking for a way to optimize this, preferably to execute it within only one query on the database. Is this possible? -
Data from dynamically created inputs table is not passing to backend
I am trying to pass multiple data from an input table (with row addable option) in the backend and for saving them in my database. Here I try to use Django and MongoDB. My frontend's JS & HTML code is: let i = 1; function rowTemplate(i) { return `<tr data-index=${i}> <td>${i}</td> <td><input type="text" name="name-${i}"></td> <td><input type="text" name="roll-${i}"></td> <td><input type="email" name="email-${i}"></td> <td><input type="text" name="password-${i}"></td> <td><input type="text" name="address-${i}"></td> <td><i class="fa fa-times-circle" style="font-size: 22px; color: red;" onclick="removeRow(${i})"></i></td> </tr>` } for (i = 1; i <= 4; i ++) { $('.my_dynamic_table').append(rowTemplate(i)); } function removeRow(i) { $(".my_dynamic_table").find(`tr[data-index='${i}']`).remove(); } function addRow() { $('.my_dynamic_table').append(rowTemplate(i)); i++; } <div class="container my-5"> <h2>Welcome to dynamic input table with row adding option</h2> <form class="" method="POST"> {% csrf_token %} <table class="table table-hover my-5"> <thead class=""> <tr> <th>No</th> <th>Name</th> <th>Roll</th> <th>Email</th> <th>Password</th> <th>Address</th> <th>Remove?</th> </tr> </thead> <tbody class="my_dynamic_table"> </tbody> </table> <div class="row m-0"> <button class="btn btn-warning" onclick="addRow()">Add row</button> <button type="Submit" class="btn btn-primary ml-auto">Submit</button> </div> </form> </div> <head> <title></title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <!-- animated css link --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"/> <!-- font awsome css link --> <link rel="stylesheet" … -
Is there anything wrong with my Django urls.py code?
I have been developing a django app and the URL i want to go to says it's 404 Not Foundbecause there is a space in between the URL??? (see URL no. 10 below) Is there anything wrong with my code??? urls.py in meditatetimer app: from django.urls import path from .views import main, stop urlpatterns = [ path('', main), path('/stop', stop) ] urls.py in project: from django.contrib import admin from django.urls import path, include from django.urls.conf import include urlpatterns = [ path('admin/', admin.site.urls), path('', include('landing.urls')), path('roles/productivity/planner/', include('planner.urls')), path('roles/productivity/memo/', include('memo.urls')), path('roles/productivity/focus-timer/', include('focustimer.urls')), path('roles/meditation/meditate-timer/', include('meditatetimer.urls')), path('roles/meditation/diary/', include('diary.urls')), path('roles/meditation/qotd/', include('qotd.urls')), ] views.py in meditatetimer app: from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import TimeForm from .models import Event def main(request): time_form = TimeForm(request.POST or None) if request.method == "POST": #if time_form.is_valid(): time_form.save() return redirect('/roles/meditation/meditate-timer') else: time_form = TimeForm() timer = Event.objects.all() context = { 'timer': timer, 'time_form' : time_form, } return render(request, 'index.html', context) def stop(request): timer = Event.objects.all() timer.delete() return redirect ('/roles/meditation/meditate-timer') if I remove the slash in meditatetimer's url would only show the same thing, but now it's roles/meditation/meditate-timer/ stop (the space will still be there) Thank you in advance, I'd really appreciate any help. -
Django registration form in two steps depending on usertype
I'm quite new with Django but now I'm working on a project that needs a universal user registration and after that create a second form to save some other profile fields based on usertype. I have create this: model.py # Create your models here. class User(AbstractBaseUser, PermissionsMixin): USER_CHOICES = ( ('galerist', 'GALERISTA'), ('collector', 'COLLECTOR'), ('artist', 'ARTISTA'), ('curator', 'CURADOR'), ('general', 'GENERAL'), ('press', 'PRENSA') ) username = models.CharField(max_length=20, unique=True) usertype = models.CharField(max_length = 20, choices = USER_CHOICES, default = 'normal') image = models.ImageField(upload_to='media',blank=True, null=True) email = models.EmailField() nombre = models.CharField(max_length=30, blank=True) apellidos = models.CharField(max_length=30, blank=True) telefono = models.CharField(max_length=12, blank=True) empresa = models.CharField(max_length=30, blank=True) direccion = models.CharField(max_length=100, blank=True) ciudad = models.CharField(max_length=15, blank=True) pais = models.CharField(max_length=20, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = UserManager() def get_type(self): return self.usertype def get_full_name(self): return self.nombre + ' ' + self.apellidos def __str__(self): return self.username class CollectorProfile(models.Model): VISITA_CHOICES = ( ('1', '1'), ('2', '2'), ('3+', '3+'), ('Nunca', 'NUNCA') ) COMPRA_ARTE_CHOICES = ( ('1+', 'Más de una vez al año'), ('1-2', 'Cada 1 - 2 años'), ('3-5', 'Cada 3 – 5 años'), ('1era', 'Estoy buscando comprar mi primera obra') ) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=64) company … -
Facing Issue when giving restricted permissions to particular group in Django
I am trying to make a REST API using Django REST Framework. In the section of Authentication and Authorization I created 2 groups namely Manager (which has permissions to perform CRUD on database) and Staff (which has only view permission). Using serializers I am displaying the data in json format. But I am still able to perform CRUD operation using Staff account. How can I fix that? REST API View -
Override Django allauth SignupView to create ForeignKey object in custom user model
I have a custom User model with a FK : # users.models.py class User(AbstractUser): company = models.ForeignKey("Company", related_name="members", on_delete=models.PROTECT) # other fields I want a user to be able to send an invitation to someone else by mail with a custom link with a token in the url : # users.urls.py app_name = "users" urlpatterns = [ path("signup/", view=views.account_signup_view, name="account_signup"), path("signup/<uuid:token>", view=views.account_signup_view, name="account_signup_token"), So I write a view that inherit the SignupView of allauth # users.views.py class AccountSignupView(SignupView): def __init__(self,*args,**kwargs): super(SignupView, self).__init__(*args,**kwargs) def form_valid(self, form, *args, **kwargs): token_value = kwargs.get('token', '') self.user = form.save(self.request) if token_value: try: token = Token.objects.get(value=token_value) if token.expired: raise ObjectDoesNotExist else: self.user.company = token.company except ObjectDoesNotExist: return HttpResponse("Invitation expired or invalid") else: self.user.company = Company.objects.create() self.user.save() response = super(SignupView, self).form_valid(form) return response The line self.user = form.save(self.request) raises an IntegrityError since company is empty and SignupForm has no commit kwargs. Otherwise I could save(commit=False) I've tried to adapt the save method of allauth SignupForm but it gives me more and more problems since key is empty # users.forms.py class SignupFormCommit(SignupForm): def save(self, request, token=None): adapter = get_adapter(request) user = adapter.new_user(request) if commit: adapter.save_user(request, user, self) self.custom_signup(request, user) setup_user_email(request, user, []) else: adapter.save_user(request, user, self, commit=False) return … -
How do I use django_tables2 with a filter?
I'm displaying data on a webpage, and I would like to migrate this code to use the table I created in tables.py. I can't figure out how to do it without breaking the filter. views.py def PlatListView(request): queryset = Plat.objects.all().values('id', 'description','status', 'phase__number','phase','schedule_found').annotate(lot_count=Sum('phase__lot_count')).order_by('description') f = PlatFilter(request.GET, queryset=queryset) return render(request, 'blog/filtertable2.html', {'filter': f}) filters.py class PlatFilter(django_filters.FilterSet): community = ModelChoiceFilter(queryset=Community.objects.all()) tables.py import django_tables2 as tables class PlatTable(tables.Table): id = tables.Column() description = tables.Column() status = tables.Column() phase__number = tables.Column() lot_count = tables.Column() schedule_found = tables.Column() class Meta: ordering = 'description' #model = Plat -
Able to run Django server on PyCharm but not on command line?
I configured my virtual environment with virtualenvwrapper and I can run the server when I hit the run button on PyCharm. But when I type in manage.py runserver on my command line, I get this error message. raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I'm using the PyCharm .env plug-ins to export my variables. And my .env file is sitting on the root of my project folder. -
How to add chat feature in django web
I made A Django app which has sign Up/log in feature I want To Add "Chat feature in this app" which allows different user to connect and communicate with each other seprately after verifying their credentials. Could any one help me how to do this? -
pyjwt[crypto] 2.0.0 update incompatible with django-allauth
I have a project that uses django-allauth 0.44.0. Yesterday (12/22/20) pyjwt update your version to 2.0.0. When i try to install my dependencies running pip, return this error message, using docker-compose: Collecting pyjwt[crypto]>=1.7 ERROR: In --require-hashes mode, all requirements must have their versions pinned with ==. These do not: pyjwt[crypto]>=1.7 from https://files.pythonhosted.org/packages/91/5f/5cff1c3696e0d574f5741396550c9a308dde40704d17e39e94b89c07d789/PyJWT-2.0.0-py3-none-any.whl#sha256=5c.... (from django-allauth==0.44.0->-r requirements-dev.txt (line 125)) ERROR: Service 'web' failed to build: The command '/bin/sh -c pip install -r requirements-dev.txt' returned a non-zero code: 1 In Poetry.lock: [[package]] name = "django-allauth" version = "0.44.0" description = "Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication." category = "main" optional = false python-versions = "*" [package.dependencies] Django = ">=2.0" pyjwt = {version = ">=1.7", extras = ["crypto"]} python3-openid = ">=3.0.8" requests = "*" requests-oauthlib = ">=0.3.0" [[package]] name = "pyjwt" version = "1.7.1" description = "JSON Web Token implementation in Python" category = "main" optional = false python-versions = "*" Anybody do have the same issue? Thanks -
TemplateDoesNotExist at /. i dont know where i'm wrong
I don't know where i'm wrong, i'm fairly new to this so please tell me where i'm wrong. help me please, this is views.py from django.shortcuts import render def home(request): return render(request, 'home.html') urls.py """portfolio URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home) ] path manage.py db.sqlite3 views.py urls.py settings.py asgi.py wsgi.py __init__.py templates/home.html i'm using Django 3.0.10 -
How can I add image saved in the file system to the ImageField in the model?
I am trying to genera .svg QR code, save it to the file system and somehow map it with ImageField in the model. I do not really get what and how I should put into the model, so it would be "linked" with the image file. Please help me find the way. :) models.py class PinModel(models.Model): pin = models.CharField(max_length=6, unique=True) user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) qr = models.ImageField(upload_to='qr/', blank=True, null=True) views.py class PinView(viewsets.ModelViewSet): queryset = PinModel.objects.all() serializer_class = PinSerializer def create(self, request, *args, **kwargs): pin = "123456" img = qrcode.make(pin, image_factory=qrcode.image.svg.SvgImage) # img is my SvgImage object img.save("qr/qrcode.svg") # now I just drop it here pin_post = PinModel.objects.create(pin=pin, user=user) # I've tried to add (qr=img) here serializer = PinSerializer(pin_post) return Response(serializer.data, status=status.HTTP_200_OK) So at this point, I have qrcode.svg in qr folder, but my PinModel is being created with Null values. I have tried to just save img, but that did not help me much. Later I am planning to generate word document with PinModel details and these svg images. How can I add image saved in the file system to the ImageField in the model? Thanks everyone! -
Get information from many to many fields in django
My model: class User_Detail(models.Model): username = models.CharField(max_length=50, unique=True, null=False) email = models.EmailField(unique=True, null=False) password = models.CharField(max_length=50) auth_token = models.CharField(max_length=100, default=None, null=True) class Board(models.Model): unique_id = models.CharField(max_length=100, null=False, unique=True) created_by = models.ForeignKey(User_Detail, on_delete=models.CASCADE, related_name="board_creator") name = models.CharField(max_length=100, null=False, unique= True) # membership class UserBoardMapping(models.Model): user = models.ManyToManyField(User_Detail) board = models.ManyToManyField(Board) user_type = models.CharField(max_length=10, choices=USER_TYPE, default='moderator') How can I get all the users who are members of a particular board id? I want user information in my output with the board id. -
How to merge Multiple URL's in a Single URL in Django?
I ahve multiple url's for sitemap in my website, but I want to merge all sitemap url's with a single url, I create different-2 sitemap according to my requirement, but now i want to display all those urls in a single url, Here is my urls.py file.. path('sitemap/sitemapblog.xml', sitemap, {'sitemaps': sitemapblog}), path('sitemap/sitemapproject.xml', sitemap, {'sitemaps': sitemapproject}), path('sitemap/sitemaplocation.xml', sitemap, {'sitemaps': sitemaplocation}), path('sitemap/sitemaplocality.xml', sitemap, {'sitemaps': sitemaplocality}), path('sitemap/sitemapbuilder.xml', sitemap, {'sitemaps': sitemapbuilder}), path('sitemap/sitemapcategory.xml', sitemap, {'sitemaps': sitemapcategory}), path('sitemap/sitemapsearchtag.xml', sitemap, {'sitemaps': sitemapsearchtag}), I want to merge these all url's in a single url... path('sitemap.xml', sitemap, {'sitemaps': sitemapblog, 'sitemaps': sitemapproject, 'sitemaps': sitemaplocation}), i want to merge in above sitemap.xml file... i have done as this, but I examplae.com/sitemap.xml is displaying sitemap/sitemaplocation.xml this sitemap data, please let me know how i can display only above urls in sitemap.xml. -
How do I generate a message in a User Edit View using Django
I am trying to generate a message when someone edits their user profile. The code that I have created is below. The profile gets updated and returns me to my home page, but doesn't generate a message. Please help. Thanks. base.html {% if messages %} {% for message in messages %} {{ message }}<br/> {% endfor %} {% endif %} views.py from django.contrib import messages class UserEditView(generic.UpdateView): form_class = EditProfileForm template_name = 'registration/edit_profile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user def get_success_message(self): msg = 'Profile has been updated!' messages.add_message(self.request, messages.INFO, msg) -
Django Joining Tables
I am trying to get the information from one table filtered by information from another table (I believe this is called joining tables). I have these two models: class Listing(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=500) price = models.DecimalField(max_digits=11, decimal_places=2, validators=[MinValueValidator(Decimal('0.01'))]) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="") imageURL = models.URLField(blank=True, max_length=500) creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator", default="") isOpen = models.BooleanField(default=True) def __str__(self): return f"{self.id} | {self.creator} | {self.title} | {self.price}" class Watchlist(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listingWatched", default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userWatching", default="") What I need to do is to get all the listings from a specific user Watchlist, the idea is to generate a page with all of the information of each of the listings that are in the user's watchlist. What should I do? Thanks in advance! -
Need to display data from mysql into a table in a modal using django
I am creating a web app which has several buttons which has different functions. When a button is pressed I need to display data (a users data table from mysql database) into a modal without reloading the page. I have used django along bootstrap for building my webapp.Here is my code views.py from django.shortcuts import render, redirect from django.db import connection import datetime from django.contrib import messages def edit_parameter_view(req): #Some_code_here def create_user_view(req): #Some_code_here def show_users_view(req): brcd=req.session['brcd'] with connection.cursor() as cursor: cursor.execute("SELECT * from gl.users WHERE brcd=%s" % (brcd)) data = cursor.fetchone() return render(req, 'edit_parameter.html',{'data':data}) The data here is the table which has the various attributes of the user such as username,userid,password,addres,etc. I need this table to show in moadal of my webpage. edit_parameter.htm {% load static %} <!DOCTYPE html> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="IE=edge" http-equiv="X-UA-Compatible"> <meta content="width=device-width, initial-scale=1" name="viewport"> {%block title %} <title>Success</title> {% endblock %} <link crossorigin="anonymous" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" rel="stylesheet"> <style> #css </style> {% block content %} <form action="{% url 'update' %}" method="post"> {% csrf_token %} <table BORDER=0 style="float: left; margin-top:1px; margin-left:30px;"> #table </table> <table> <td><button type="button" class="btn btn-danger custom" onclick="this.form.action='{% url ' create_user' %}';this.form.submit();">Add New User</button></td> <td><button type="button" class="btn btn-danger custom" onclick="this.form.action='{% … -
Converting Django from SQLite to PostgreSQL
I'm new to Python and Django. I've purchased a book, Django 3 by example (3rd Edition) and really enjoying the lessons. I'm in chapter 3 now and the goal is to enhance the search engine functionality. In order to do so, the book has steps to convert the DB to PostgreSQL. I'm following the directions below and I've tried several things to fix the issue that I've found on Google. I can't seem to find the answer. Steps: install PostgreSQL: sudo apt-get install postgresql postgresql-contrib install psycopg2: pip install psycopg2-binary==2.8.4 create user for PostgreSQL database. Open the shell and run the following commands. a) su postgres b) createuser -dP blog Enter a password for the new user and then create the blog database and give ownership to the blog user you just created with the following command: createdb -E utf8 -U blog blog Edit the settings.py file... steps omitted. I'm stuck on step 3a above. I get asked for a password for postgres and nothing seems to work. I have tried some things found on google as well. Here is what I've tried. sudo -u postgres psql \password postgres enter and confirm password \q Try to log back in using … -
I am trying to inject an already rendered Django template into a section of my page using AJAX
I am following by this tutorial on how to get live updates on django without refreshing the page. The tutorial uses flasks render_template to get the html rendered which is then injected to a page section. I am trying to do the same in Django, But django just directly renders it in the browser... I don't want that. I just want django to send the rendered html response to AJAX which could then inject that to a section on my live page. Here is the code : views.py class ManageView(LoginRequiredMixin, View): template_name = "dashboard/manage.html" context = {} def get(self, request, app_id, folder_id=None): app = App.objects.get(pk=int(app_id)) self.context["app"] = app if folder_id: try: self.context["folder"] = Folder.objects.get(id=folder_id) except: self.context["folder"] = app.folder else: self.context["folder"] = app.folder return render(request, self.template_name, self.context) def post(self, request, app_id, folder_id=None): try: files = request.FILES.getlist('files_to_upload') folder_name = request.POST.get("folder") master = request.POST.get("master") if master: master = Folder.objects.get(id=master) if folder_name: Folder.objects.create(name=folder_name, owner=request.user.customer, folder=master) if files: for file in files: if file.size < settings.MAX_FILE_SIZE: File.objects.create(folder=master, item=file, name=file.name, size=file.size) app = App.objects.get(pk=int(app_id)) self.context["app"] = app if folder_id: try: self.context["folder"] = Folder.objects.get(id=folder_id) except: self.context["folder"] = app.folder else: self.context["folder"] = app.folder return render(request, 'dashboard/filesection.html', self.context) except DatabaseError: return render(request, "dashboard/index.html", self.context) urls.py urlpatterns = [ url(r'^manage/(?P<app_id>[0-9]+)/(?P<folder_id>.+)', … -
Can't pip install django-dash
I have django and dash installed but not django-dash. Any ideas why this wont work? I've tried both: pip install django_plotly_dash pip install django-dash Command Prompt Error: ERROR: Could not find a version that satisfies the requirement django_plotly_dash (from versions: none) ERROR: No matching distribution found for django_plotly_dash