Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-templated-email does not send email
I am using the following package https://github.com/vintasoftware/django-templated-email in a Django app to try and send an email. I am running it inside a django management command. When I run the command the email part outputs to the console but no email is actually sent out. The SMTP settings and such are correct as emails work fine for other areas of the application. from templated_email import send_templated_mail send_templated_mail( template_name='welcome', from_email='from@example.com', recipient_list=['to@example.com'], context={ 'username':"test", 'full_name':"test", 'signup_date':"test" }, ) Any help is appreciated. I suspect I have misunderstood the syntax of the package. -
Django3: How to display the results of a model function into an HTML template and/or Admin
So I have the following Classes one for user and one for "Project": class CustomUser(AbstractUser): pass class Project(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False) name = models.CharField(max_length=20, editable=False) total = models.DecimalField(max_digits=6, decimal_places=2, editable=False) created = models.DateTimeField(auto_now_add=True, editable=False, null=False, blank=False) def monthlyTotal(self,user): this_month = now().month return Project.objects.filter( created__month=this_month, user=user ).aggregate( sum_total=Sum('total') )['sum_total'] def __str__(self): return self.name and my view which is also used to populate the Project Class: def homepage(request): if request.method == "POST": project = Project() name = request.POST.get('name') total = request.POST.get('total') created = datetime.datetime.now() user = request.user project.user = user project.name = name project.total = total project.created = created project.save() #return HttpResponse(reverse("homepage.views.homepage")) return render(request, 'homepage.html') else: return render(request, 'homepage.html') I would like to pass the currently logged in user to the function monthlyTotal so that it displays on my template. This is what I tried so far <p>Total monthly sales = {{ Project.monthlyTotal(user.username) }}</p> <p>Total monthly sales = {{ Project.monthlyTotal(request.user) }}</p> but can't get it to work, also would I be able to display this field in the admin so you see it when you look at a user admin portal? Thanks -
Update A Profile Picture In Django ImageField : Dynamic Method Used In Django Admin
My Application has a system where user can upload his profile pic. I created this feature later so used the foreignkey method this is the model class Profile_Pic(models.Model): user = models.ForeignKey(User, default='', null=False, on_delete=models.CASCADE, related_name='userPic') profile_pic = StdImageField(upload_to='photos', default='', blank=True, ) and the html page {% extends 'datas/base.html' %} {% block content %} {% load static %} <h1 class="text-center" style="color: white">Add Profile Picture</h1> <br><br> <div class= "col-md-6.offset-md-3"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if form.errors %} <div class="alert alert-warning alert-dismissable" role="alert"> <button class="close" data-dismiss="alert"> <small><sup>x</sup></small> </button> <p>Data Error, Please Check Again.....</p> {% for field in form %} {% if field.errors %} {{ field.errors }} {% endif %} {% endfor %} </div> {% endif %} {{ form.as_p }} <input type="submit" value="Save" class="btn btn-primary"> </form> </div> {% endblock %} the view @login_required def profile_pic(request): if request.method == 'POST': form = Photo(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() messages.success(request, 'Your Profile Picture Has Been Updated Successfully') return redirect('profile') else: form = Photo() return render(request, 'datas/user_image.html', {'form': form}) and finally the form class Photo(forms.ModelForm): class Meta: model = Profile_Pic fields = ['profile_pic'] widgets = { 'Add Profile Pic': forms.FileInput(attrs={'class': 'form-control'}), } Now when we upload from the admin site,the system automatically deletes … -
Braintree hosted fields not appearing when using server side generated client token
I'm using the hosted fields example from braintree: https://developers.braintreepayments.com/guides/3d-secure/client-side/javascript/v3 Inside their javascript there is a function which calls: https://braintree-sample-merchant.herokuapp.com/client_token function getClientToken() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 201) { onFetchClientToken(JSON.parse(xhr.responseText).client_token); } }; xhr.open("GET", "https://braintree-sample-merchant.herokuapp.com/client_token", true); xhr.send(); } I substitute that endpoint with my own, which generates my client token using the settings I got from braintree sandbox. #settings.py from braintree import Configuration, Environment Configuration.configure( Environment.Sandbox, BT_MERCHANT_ID, BT_PUBLIC_KEY, BT_PRIVATE_KEY ) #views.py import braintree def return_client_token(request): return JsonResponse({ "client_token": braintree.ClientToken.generate() }) My endpoint returns the client token, but when I use it, the hosted fields do not materialize. The length of the key from the Braintree's example endpoint is 3664, whereas my is 2364. -
Is there a django package which locks certain objects / records?
How to prevent a user from editing an object / record already being edited from another? Obviously this would be easy enough to design myself. I guess I would want a model a bit like the ContentType model. A column for appname, a column for model, a column for primary key, and a column for the user currently editing the record. Whenever somebody requests a URL the software checks this table to see if another is already editing the record. If there is, this user would see a message like "Record currently being edited by user ..." Is there a package which does this to save me the effort? To be clear I'm not talking about locking the row at the SQL level or Django auth permissions. -
How to make a django field choosable
I need to define one field of my django model in a way that takes either X/Z, True/False or 0/1. I mean when I select one checkbox I expect be able to choose just one checkbox not both together(Like select between Yes or No) and after submit I see one of those mentioned values in the database table field. What I have tried so far: class Post(models.Model): STATUS = Choices( (1, 'x', ('select X')), (2, 'z', ('Select Z')) ) action_style = models.CharField( max_length=32, choices=STATUS, default='x' ) and in form: class Postform(forms.ModelForm): STATUS = Choices( (1, 'x', ('select X')), (2, 'z', ('Select Z')) ) status = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, required=False, choices=STATUS ) class Meta: model = Post fields = ['status'] and in template: <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.status }} <input type="submit" value="submit"/> </form> -
Django object of type 'method' has no len()
I just added pagination to a ListView in Django, but it is returning object of type 'method' has no len() error, even though I am overriding the get_queryset method and it is not returning anything different from the queryset. The view causing the error looks like this: class ProductList(ListView): paginate_by = 10 model = Product context_object_name = 'products' template_name = 'catalog/product/product_list.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def queryset(self): categories = Category.objects.filter(company=self.request.user.profile.company) return Product.objects.filter(category__in=categories) def get_context_data(self, **kwargs): context = super(ProductList, self).get_context_data(**kwargs) context['customers'] = Customer.objects.filter(company=self.request.user.profile.company) context['categories'] = Category.objects.filter(company=self.request.user.profile.company) return context How am I supposed to paginate with an overriden queryset without it showing this error? -
How can group this relations on Django Rest Framework
Currently, I've the next models: class Variant(models.Model): name = models.CharField('name', max_length=60) class VariantValue(models.Model): value = models.CharField('value', max_length=60) variant = models.ForeigKey('variant', to=Variant, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField('name', max_length=60) I want to get the next json result: { "name": "My product", "variants": [ { "variant_id": 1, "values": ["Value 1", "Value 2", "Value 3"] }, { "variant_id": 2, "values": ["Value 4", "Value 5", "Value 6"] }, ] } It's possible with a Serializer or do I've to make the json manually? I just have the next ModelSerializer: class ProductModelSerializer(serializers.ModelSerializer): variant_list = serializers.SerializerMethodField('get_variant_list', read_only=True) class Meta: model = Product fields = [..., 'variant_list'] def get_variant_list(self, obj): variant_list = VariantValue.objects.filter(product_id=obj.id) variant_list_grouped = variant_list.values('variant', 'value').annotate(count=Count('variant')) res = [] for variant in variant_list_grouped: pass return [] Thanks! -
MultiValueDictKeyError at /signup/ 'password11'
I'm trying to signup user but getting some weird error. please help me to solve it This is my view file with the function named signup def signup(request): if request.method=='POST': username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password11 = request.POST['password11'] if password1==password11: if User.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('/account') elif User.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('/account') else: user=User.objects.create_user(username=username, password=password1, email=email) user.save(); auth.login(request,user) print('user created') else: messages.info(request,'Password not Matching') return redirect('/account') return redirect('/') else: return render(request,'account.html') And this is my signup file. I've save file with the name account.html. <form id="regform" style="margin-top: -40px;" action="/signup/" method="post"> {% csrf_token %} <input type="text" placeholder="Username" name="username"> <input type="email" placeholder="Email" name="email"> <input type="password" placeholder="Password" name="password1"> <input type="password" placeholder="Confirm Password" name="Password11"> <button type="submit" id="btn2">Register</button> <div> {% for message in messages %} <h6>{{message}}</h6> {% endfor %} </div> </form> -
docker-compose.yml for production - Django and Celery
I'm looking to deploy a simple application which uses Django and celery. docker-compose.yml: version: "3.8" services: django: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app/ ports: - "8000:8000" environment: - DEBUG=1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=djcelery.backends.database:DatabaseBackend depends_on: - redis celery: build: . command: celery -A core worker -l INFO volumes: - .:/usr/src/app environment: - DEBUG=1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=djcelery.backends.database:DatabaseBackend depends_on: - django - redis redis: image: "redis:alpine" volumes: pgdata: Dockerfile: FROM python:3.7 WORKDIR /app ADD . /app #Install dependencies for PyODBC RUN apt-get update \ && apt-get install unixodbc -y \ && apt-get install unixodbc-dev -y \ && apt-get install tdsodbc -y \ && apt-get clean -y # install ODBC driver in docker image RUN apt-get update \ && curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \ && curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list \ && apt-get update \ && ACCEPT_EULA=Y apt-get install --yes --no-install-recommends msodbcsql17 \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* \ && rm -rf /tmp/* # install requirements RUN pip install --trusted-host pypi.python.org -r requirements.txt EXPOSE 5000 ENV NAME OpentoAll CMD ["python", "app.py"] Project Directories: When I run "docker-compose up" locally, the celery worker is run and I am able to go to localhost:8000 to … -
Django - 404 static in Docker on react app
I have backend on Django and storefront/dashboard on React. Django in docker container. Dockerfile (Django) ### Build and install packages FROM python:3.8 as build-python RUN apt-get -y update \ && apt-get install -y gettext \ # Cleanup apt cache && apt-get clean \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY requirements_dev.txt /app/ WORKDIR /app RUN pip install -r requirements_dev.txt ### Final image FROM python:3.8-slim RUN groupadd -r saleor && useradd -r -g saleor saleor RUN apt-get update \ && apt-get install -y \ libxml2 \ libssl1.1 \ libcairo2 \ libpango-1.0-0 \ libpangocairo-1.0-0 \ libgdk-pixbuf2.0-0 \ shared-mime-info \ mime-support \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* RUN mkdir -p /app/media /app/static \ && chown -R saleor:saleor /app/ COPY --from=build-python /usr/local/lib/python3.8/site-packages/ /usr/local/lib/python3.8/site-packages/ COPY --from=build-python /usr/local/bin/ /usr/local/bin/ COPY . /app WORKDIR /app ARG STATIC_URL ENV STATIC_URL ${STATIC_URL:-/static/} RUN SECRET_KEY=dummy STATIC_URL=${STATIC_URL} python3 manage.py collectstatic --no-input EXPOSE 8000 ENV PYTHONUNBUFFERED 1 CMD ["gunicorn", "--bind", ":8000", "--workers", "4", "--worker-class", "uvicorn.workers.UvicornWorker", "saleor.asgi:application"] When I go to the Dashboard and access objects with pictures, I get error: error on Dashboard Thanks for help me! -
Fill list using Counter with 0 values
Is possible to have a count of how many times a value appears in a given list, and have '0' if the item is not in the list? I have to use zip but the first list have 5 items and the other one created using count, have only 3. That's why I need to fill the other two position with 0 values. -
Django - export one-to-many in csv using one row per foreign key
I have a postgres database in Django and one of the tables has a foreign key and a number of entries. I want to generate a csv file with one row per foreign key. i.e. this is the table AuthorID Bookname Price 1001 “I love django” 3.40 1001 “Python is cool” 4.20 1002 “Pandas is cool” 5.10 The resulting csv should look like this AuthorID,Bookname1,Price1,Bookname2,Price2 1001,I love django,3.40,Python is cool,4.20 1002,Pandas is cool,5.10,, Can you help me with that? Is there a native way to do it in Django or in Postgres using raw sql? Thanks -
Question about EnviromentFile config setting for Gunicorn and Django production, do I need to use it?
I have a Django app in production, using gunicorn for help. I have a question about the setting EnviromentFile, should I refence the venv path for my project? Is it mandatory? The reason why I'm not adding it in my service file, is because I'm not serving any variables through the env. /etc/systemd/system/gunicorn.service : [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=user Group=www-data WorkingDirectory=/home/user/alpha/project ExecStart=/home/user/alpha/project/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ project.wsgi:application [Install] WantedBy=multi-user.target Do I still need to add, EnviromentFile,to my file above? And if I do, is referencing the activation needed? Like so: EnviromentFile=PATH/TO/venv/bin/activate? -
How do I get datatables to work with bootstrap4 tabs in Django templates?
I have a Django template with multiple tables. I am using Bootstrap 4 with datatables. I wanted to put my tables in tabs, and that is giving me problems. If the tables are not in tabs, this code works fine: $(document).ready(function() { $('.datatable').DataTable( { dom: 'Blfrtip', buttons: [ 'copy', 'csv', 'excel', 'print' ] } ); } ); I looked at these two links: Scrolling and Bootstrap tabs and Hidden initialisation. And got the snippet at the bottom of this post to work as datables (though the table widths have issues in Django). However, that snippet only works with hard-coded tables. In my Django template, I am using template tags to loop through query strings like this: {% if items %} <table class="table table-striped table-valign-middle datatable" id="data"> <th>Item Table</th> <thead> <tr> <th>Title</th> <th>Price</th> <th>Date</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{ item.item.title|truncatechars:25 }}</td> <td>{{ item.price }}</td> <td>{{ item.date }}</td> </tr> {% endfor %} </tbody> </table> {% else %} <div class="text-center font-weight-bold"> No items </div> {% endif %} In Django using the snippet example, if I replace the first tab's hard coded table with that template for loop, the datatable only works for the first tab (i.e., no … -
PUT POSTGRESQL DATABASE ONLINE
I'm working on a Django Project in which I'm using a postgresql database. Now I have to put my project online on python anywhere, but I looked at some videos and they put the database on AWS. I don't understand why can't I put also the database on python anywhere but I have to put it on AWS for example. I'm sorry if it is a dumb question but this is my first experience with backend. -
How to send a JavaScript variable to Django to use in views.py
I have a model that contains information about the different buildings being displayed on my website. When a user selects one of the buildings I would like that information to be displayed. When the user selects a building, a JavaScript variable contains the building name that the user selected. How can I send this variable to my views.py so I can get the building object specified by the "name" JavaScript variable? Here is what I currently have for my views.py, the building name "Harris" is hard coded in. This is where I would like to put the JavaScript variable, so I can display the buildings information depending on which one the user selects. from django.shortcuts import render from django.http import HttpResponse from .models import Building def index(request): buildings = Building.objects.get(buildingName = "Harris") return render(request, 'index.html', {'buildings': buildings}) I am new to Django so any information is helpful. Thanks -
How to use django ORM to query database
I have a model called 'dboinv_product' and this model has a field called 'product_name' I need to use Django ORM in my views.py file to pull ALL the product names. The goal is to put it into a list this way I can serialize it using JSON. Does anyone know which Django command(s) can be used to produce this list? Essentially, I need the equivalent of "SELECT ALL product_name FROM dbo.inv_product" -
Algorithm: track relationship changes of 3 elements
I want to log changes in 2 elements related to a 3rd one, but I can't come up with a nice algorithm to it. Let there be 3 objects (or components) that can be installed one inside the other (like russian dolls), and their state change when you put them in or take them out: A is installed in B and B is installed in C. A is taken out of B, but B still is in C. (A becomes avaiable) A and B are taken out of C. (A and B become available) I have 3 different classes defining the 3 components, but I'm not sure how to log the changes... on the same object? on a different class just for logging? Is there a pattern I should use as a base case? COMPSTATUS = ((1,'Available'),(2,'In use')) class A(models.Model): id = models.AutoField(primary_key=True) class B(models.Model): id = models.AutoField(primary_key=True) compA = models.ForeignKey(A, on_delete=models.PROTECT) status = models.CharField(max_length=2,choices=COMPSTATUS,default='1') class C(models.Model): id = models.AutoField(primary_key=True) compB = models.ForeignKey(B, on_delete=models.PROTECT) status = models.CharField(max_length=2,choices=COMPSTATUS,default='1') -
django tcp connection to models, FATAL: sorry, too many clients already database
First, let me say that I am new to Python i connected to djnago with tcp socket and i run the server with custom script and setup.djangu(), i get , create, and updated models with tcp and works fine , but problem is if 100 user coonected to a socket and be online i get this exception conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: sorry, too many clients already And I'm going to have a lot more online users than that,this is interesting to me i get online query from from django.db import connection and i see just two connection is online, if i connected with django plugin why other connections wont show, My question is how can I control postgress connections and use one or multi conecction to database, not per user in django with tcp connection, and i can work with django syntax ? thanks -
How to use dynamic urls to go to a database item
How do I make my website that going to the url 'mywebsite.com/1/' would show an item in the database that's id is 1 (and the same for /2/, /3/, etc.)? All the tutorials I have found are for setting up 'urls.py' in the older versions of Django. -
filter queryset of unique objects in django
Hi, I have a model in django lets say UserProfile and it has some data as like this. I want to filter over this model in such a way that if there are multiple records for same user_auth_id (for example user_auth_id=279) then I will take the last one. By this way I want to get the queryset from this model. What will be the filter expression here? From this example my queryset will be [247, 248, 249, 250, 251, 252, 312, 254, 255, 260, 262] -
Respect django tables order
is there any way to make django respect the data base order once I make migrations?, I constantly make some changes and when I see the data base tables the order changes and it is a bit disgusting. -
Django redirect URLs in modal forms
I am new with Django so I created a delete_orders modal form and now I want to redirect to the true path after deleting the order. My views.py is something like: def deleteOrder(request, order_id): order_item = Order.objects.get(id=order_id) customer = order_item.customer.username url = request.META['HTTP_REFERER'] parsed_url = urlparse(url) url_path = parsed_url.path if '/panel/profile/' in url_path: url_path = '/panel/profile/' + customer if request.method == 'POST': order_item.delete() return redirect(url_path) context = {'order_item': order_item} return render(request, '', context) And my urlpatterns is: path('<int:order_id>', views.deleteOrder, name='delete_order'), I want to know if it is a good practice to do the job or we have some other standard solutions? -
How to link some users with an OAuth application to allow or deny authentication based on that application in django-oauth-toolkit?
I'm using django-oauth-toolkit to do user authentication with DRF, my goal is to allow or deny authentication based on the OAuth application linked to the user. Let's say that I have application-one with user-a linked to it and application-two with user-b linked to it, now if user-a or user-b tries to provide different client_id:client_secret than the one for that OAuth application each one is linked to it, authentication should be denied. That's useful because if I created two OAuth applications, one for android users and the other for web users I can deny authentication for users who are not linked to with requested OAuth application or allow access for users who are linked to the correct OAuth application. I didn't find anything useful in the docs or over the internet about linking some users or for that purpose although it sounds very helpful, so any tips or suggestion will be appreciated. Thanks