Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django order_by on a nested JSONField
I have JSONField on my Product model and in this model, I have nested fields. For example: "data": { 'products':{ "name": "ProductA", "color": "Brown", "price": { "end_user": 54, "credit_cart": 60 }, "name": "ProductB", "color": "Red", "price": { "end_user": 100, "credit_cart":120 }, } } I want to order nested ``end_user``` field. -
How to take a build of python project to deploy it as a website for public
i am very much interested to learn python nd do more projects in it. As a starting a did a small django app. it runs an my local machine successfully. I need to know how o take a build of my project to deploy it as a web site forpublic I used python .6.6, django, pycharm did my project in Windows 10 -
Show logged in used data
How to show logged in user data, for example, email, name etc in a django form? I need to show the data in input field value attribute. For example, if I type {{ form.email.errors }} {{ form.email }} then in this form field the email id of that particular user must already be pre filled. How will I achieve this? -
django: importing models from another project not working
I am trying to import the models from another project. app/ -project1/ -project1/ - models.py (model: Article) -manage.py -project2/ -project2/ - forms.py -manage.py I am trying to make a modelForm in project2 based on the models in project 1. I tried in my forms.py: 1. Appending the path to project1 by importing sys sys.path.append(/path/to/project1) 2. sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 3. Importing directly from project1.models import Article (tried from project1.project1.models import Article too) I still can't get the import to work, and was wondering if someone could help me. Thank you so much in advance! -
Add asterisks to the mandatory fields on Django admin
I want to add asterisks to the mandatory fields on Django admin page. I add required_css_class='requried' in forms.py. And add extrastyle to task_change_form.html. {% block extrastyle %} {{ block.super }} <style type="text/css"> /* add an asterisk using CSS */ .required::after { content: "*"; } </style> {% endblock %} What is wrong with me? -
Django PostgreSQL search returning fewer than expected results
Say I have the following queryset of carrots: <QuerySet [ <Carrot: Blue carrot>, <Carrot: Purple carrot>, <Carrot: Apple carrot>, <Carrot: Yellow Carrot>, <Carrot: Green carrot> ]> I can filter for <Carrot: Apple carrot> by using: queryset.filter(name__icontains="app") However, if I try the same filter with PostgreSQL's search function: queryset.filter(name__search="app") I get an empty queryset. Why is this? Is there a way to relax the constraints of __search so that I can use the feature as a backend for a typeahead search field? -
How do I show image on the Django admin list?
How do I show image on the Django admin list? There are the following models. model.py class LawyerProfile(models.Model): lawyer_idx = models.IntegerField('ID', primary_key=True) #lawyer_idx = models.OneToOneField(Lawyer, primary_key=True, db_column='lawyer_idx', related_name='profile') lawyer_profile_path = models.CharField('PATH', max_length=200, blank=True, null=True) lawyer_profile_name = models.CharField('IMG', max_length=100, blank=True, null=True) lawyer_introduction = models.TextField('소개', blank=True, null=True) register_date = models.DateTimeField('등록일') update_date = models.DateTimeField() class Meta: managed = False db_table = 'lawyer_profile' The data in loyer_profile_path is: /lawyer/ilsangju7777@hanmail.net The data in lawyer_profile_name is: 53-658e9b9918aeb9ba38b26a5007f9872d-1543821136-62.jpg Django Admin list screenshot I want to show the image in Django Amin List with the two data combinations above. The addresses of images on the web are as follows. URL = "https://localhost.com/uploads/lawyer/" loyer_profile_path = chogm@tll.co.kt lawyer_profile_name = 67-a4b37da358091553ce3416a64b60b190-1550159583-29.jpeg URL + loyer_profile_path + "pic_" + lawyer_profile_name I'd like to make the data below and show it as an image on the list. https://localhost.com/uploads/lawyer/chogm@tll.co.kt/pic_67-a4b37da358091553ce3416a64b60b190-1550159583-29.jpeg Anyone help me? -
Create instance of foreign key object every time parent object is created
I want to create a Cart object that is linked to the User model in my database. Every time I create a User, I want a linked Cart to be created (in the database). Any suggestions? I tried linking it to the User id but no joy. models.py from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save # Create your models here. class Product(models.Model): name = models.CharField(max_length=50) desc = models.CharField(max_length=50) img = models.FileField() created = models.DateField() num_stars = models.IntegerField() class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,to_field='id', null=True) content = models.CharField(max_length=50) last_update = models.DateTimeField() -
How to remove decimal field "junk" from values in a list?
I have a sorting algorithm that gives me an ordered list based on a QuerySet list input. The data is coming from an MSSQL Database: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': '***', 'HOST': '***', 'USER': '***', 'PASSWORD': '***', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'read_only': True, }, } } The list is created with a query like so: con1 = Q(qmaQuoteID=quote_id) con2 = Q(qmaQuoteLineID=quote_line_id) query = QuoteAssemblies.objects.filter(con1 & con2).order_by('qmaQuoteAssemblyID').values('qmaQuoteAssemblyID', 'qmaParentAssemblyID', 'qmaLevel', 'qmaPartID', 'qmaPartShortDescription', 'qmaQuantityPerParent',) item_list = list(query) The sorting algorith however doesn't work because the query has some "junk" around the deciaml field values. Here is an example: {'qmaQuoteAssemblyID': 0, 'qmaParentAssemblyID': 0, 'qmaPartID': 'RACK S9 ', 'qmaLevel': Decimal('1'), 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '12U x 600 x 650 Professional Rack '} Notice how 'qmaLevel' and 'qmaQuantityPerParent' have their value surrounded by Decimal('X'). Is there a way to remove the Decimal('X') surrounding the value? -
django ForeignKey get to_field
If I make a ForeignKey definition in a model that has a to_field column definition is it possible to get that to_field value later? class author(models.Model): name=models.CharField(max_length=255) customId=models.IntegerField(default=0, null=True, unique=True) class book(models.Model): name=models.CharField(max_length=255) author=models.ForeignKey(author,to_field='customId') As shown above the foreignkey to author uses the to_field key, later on in my code I have to deal with book objects but would like to find out what field the author is linked to. -
pass the foreign key of a model in the url
I've two different models with the names TvShow and Episode but episode is connected with tvshow through a foreign key tvshow = models.ForeignKey(Media, on_delete=models.CASCADE) so I was trying to add it to urls of episode model like this path('<str:tvshow_title>/<int:season_number>/<int:episode_number>', views.episode, name='episode') but the views.py of Episode have a hard time defining it: def episode(request, tvshow_title, season_number, episode_number): tvshow = Media.objects.filter(media_type='TV', title=tvshow_title).first() episode = get_object_or_404( Episode, tvshow=tvshow, season_number=season_number, episode_number=episode_number) context = { 'episode': episode } return render(request, 'media/episode.html', context) I'm not sure what the problem is I'm not sure if this is how you pass more than one parameter to get_object_or_404. -
Running django + apache in localhost windows
i wanna try using apache as a server for django, i already add a code in the bottom httpd.conf like this WSGIScriptAlias / /D:/CodeTesting/Django/project1/project1/wsgi.py WSGIPythonHome /C:/Users/Fatoni/Envs/django WSGIPythonPath /D:/CodeTesting/Django/project1 <Directory /D:/CodeTesting/Django/project1/project1> <Files wsgi.py> Require all granted </Files> </Directory> note: i have changed documentroot apache into d:/ and i am using virtualenv in development, i am also using apache through xampp. did i make a mistake in that configuration, what kind of thing that i should do to run django in apache locally? it showing error like this after i added that code 10:06:05 [Apache] Status change detected: running 10:06:07 [Apache] Status change detected: stopped 10:06:07 [Apache] Error: Apache shutdown unexpectedly. 10:06:07 [Apache] This may be due to a blocked port, missing dependencies, 10:06:07 [Apache] improper privileges, a crash, or a shutdown by another method. 10:06:07 [Apache] Press the Logs button to view error logs and check 10:06:07 [Apache] the Windows Event Viewer for more clues 10:06:07 [Apache] If you need more help, copy and post this 10:06:07 [Apache] entire log window on the forums -
How do I figure out what dependencies to install when I copy my Django app from one system to another?
I'm using Django and Python 3.7. I want to write a script to help me easily migrate my application from my local machien (a Mac High Sierra) to a CentOS Linux instance. I'm using a virtual environment in both places. There are many things that need to be done here, but to keep the question specific, how do I determine on my remote machine (where I'm deploying my project to), what dependencies are lacking? I'm using rsync to copy the files (minus the virtual environment) -
How can i display error reperesented by json via ajax?
I am trying to submit a form via AJAX on django.The corresponding ajax code is:_ <script> $(document).ready(function(){ $('#form1').submit(function(){ console.log('form is submitted'); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); var formdata={ 'username':$('input[name=user]').val(), 'email':$('input[name=email]').val(), 'password1':$('input[name=password]').val(), 'password2':$('input[name=password1]').val(), }; console.log("Formvalue is taken"); $.ajax({ type:'POST', url:'/Submit/signingup', data:formdata, dataType:'json', encode:true, headers:{ "X-CSRFToken": csrftoken }, }) .done(function(data){ console.log(data); if(!data.success){//we will handle error console.log(data.errors); if (data.errors.email){ $('#user-group').append('<div class="warning>'+data.errors.email+'</div>'); } if(data.errors.username){ $('#email-group').append('<div class="warning>'+data.errors.username+'</div>'); } } else{ //all good } }); event.preventDefault(); }); }); The Json error message returned by server is:- How can i represent the errors in HTML?I want that each error would stick to their corresponding div elements? -
Custom style that does not allow images in django-markdown-deux
I am creating a website with Django that accepts user submitted text. I serve it back to users after converting the text to html using markdown deux, allowing some simple formatting. The problem is, I don't want to allow images. Links are fine. I know that I can create custom styles, and these styles can incorporate extras, but I cannot figure out how to simply disable image tags. The readme says all settings are optional, so I am assuming it is possible. I don't know if link-patterns in the extras could be used. The readme also says that a style is "A mapping of style name to a dict of keyword arguments for python-markdown2's markdown2.markdown(text, **kwargs)," but I can't figure out how to use this information to help me. Is there is list of keywords out there somewhere I can't find? -
How do I auto redirect from my root path?
I'm using Django and Python 3.7. I'm having an issue tryihng to redirect from my hompage ("/") to another path. I want the default root path to redirect to "/trending". I tried this urlpatterns = [ path(r'/$', redirect_to, {'url': '/trending'}), path('trending', views.trending, name='trending'), ] but am getting the error name 'redirect_to' is not defined -
CSV File into Django Template
I have an app that uploaded a file using the FileField(). Uploading the file works excellently but I have a problem on how to display the CSV file content into an HTML table where headings goes to the table header while the rows/lines of the CSV file goes to the appropriate cell in an HTML table. For now i have a little success in retrieving the CSV file's columns. Here are the snippets. Method: # retrieve datafarame's columns def get_columns(file): df = pd.read_csv(file) cols = df.columns return cols HTML: <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> {% for col in columns %} <th>{{ col }}</th> {% endfor %} </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> -
Django redirecting to a different view in another app
There are many similar questions to mine on Stack Overflow, but none which solve my problem. I have a class-based view which accepts files, and once a valid file is found, I would like the website to redirect the user to a template inside a different app, passing in some parameters. I've seen others put an extra path in 'urlpatterns' and get the view from there. But doing this only makes a GET signal on my command prompt, but not actually changing the web url. views.py from django.shortcuts import render, redirect # used to render templates from django.http import JsonResponse from django.views import View from .forms import UploadForm from .models import FileUpload class UploadView(View): def get(self, request): files_list = FileUpload.objects.all() return render(self.request, 'upload/upload.html', {'csv_files': files_list}) def post(self, request): form = UploadForm(self.request.POST, self.request.FILES) if form.is_valid(): csv_file = form.save() data = {'is_valid': True, 'name': csv_file.file.name, 'url': csv_file.file.url, 'date': csv_file.uploaded_at} # REDIRECT USER TO VIEW PASSING 'data' IN CONTEXT return redirect('project/apps/app/templates/app/home.html') else: data = {'is_valid': False} return JsonResponse(data) urls.py from django.urls import path from . import views app_name = "upload" urlpatterns = [ path('', views.UploadView.as_view(), name='drag_and_drop'), ] -
Django: No such file or directory: '/home/django/debug.log'
I'm trying to launch the following command on Mac OS X: $ python2 manage.py runserver_plus 0.0.0.0:8000 But what I'm getting is the error message ValueError: Unable to configure handler 'file': [Errno 2] No such file or directory: '/home/django/debug.log' I set up a virtual environment and activated it, but still getting this error message. What is it that I'm not doing right? -
Add product to a cart django rest framework
How can make an endpoint for adding product into a cart using django rest framework? I have searched everywhere and couldn't find. Could you help me please? This is my products.views: class ProductDetail(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer class AddProduct(ProductDetail, ListCreateApiView): serializer_class = AddToCartSerializer @require_POST def get(self, request): cart_obj = Cart.objects.get_or_new(request) product_id = request.POST.get('product_id') qs = Product.objects.filter(id=product_id) if qs.count() == 1: product_obj = qs.first() if product_obj not in cart_obj.products.all(): cart_obj.products.add(product_obj) else: cart_obj.products.remove(product_obj) request.session['cart_items'] = cart_obj.products.count() return Response(status=status.HTTP_200_OK, data={'message': 'Product has been added to cart'}) serializers.py class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ('url', 'id', 'title', 'description', 'category', 'price', 'quantity', 'in_stock', 'color') class AddToCartSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id',) -
I want to show current academic year (say 2018-19) as default field in django form and it should be updated according to the academic year
I have academic years in drop-down and I want current academic year to show in the field as default click here to see the form -
Unit Test GET API Django Rest Framework
I'm building RESTful API services using django rest framework, I've reached the point where i have to create an automated test for my RESTful API services. The sessionList api require token authentication, in case the user doesn't have the token he won't be able to access the session collection. The api worked fine when I've tested it using POSTMAN and the real browser. SessionList: class SessionList(generics.ListCreateAPIView): authentication_classes = [TokenAuthentication, ] permission_classes = [IsAuthenticated, ] throttle_scope = 'session' throttle_classes = (ScopedRateThrottle,) name = 'session-list' filter_class = SessionFilter serializer_class = SessionSerializer ordering_fields = ( 'distance_in_miles', 'speed' ) def get_queryset(self): return Session.objects.filter(owner=self.request.user) def perform_create(self, serializer): serializer.save(owner=self.request.user) Then i've created an automated test using DRF test RunningSessionTest: class RunningSessionTest(APITestCase): def test_get_sessions(self): factory = APIRequestFactory() view = views.SessionList.as_view() user = User.objects.create_user( 'user01', 'user01@example.com', 'user01P4ssw0rD') request = factory.get('http://localhost:8000/sessions/') force_authenticate(request, user=user) response = view(request) assert Response.status_code == status.HTTP_200_OK def test_get_sessions_not_authenticated_user(self): factory = APIRequestFactory() view = views.SessionList.as_view() user = User.objects.create_user( 'user01', 'user01@example.com', 'user01P4ssw0rD') request = factory.get('http://localhost:8000/sessions/') response = view(request) assert Response.status_code == status.HTTP_401_UNAUTHORIZED The issue: in both cases, if the user has the token or not the response value is HTTP_200_OK I've tried to solve the problem by trying different methods to implement the test. I've used APIRequestFactory, … -
How can I prevent CSS header from making drop downs disapear in Django form
Hello I am using modelforms . One of my entries is a ChoiceField, when I have my CSS header in the name.html file (the html file for the form page) the page does not show the drop downs. When I remove this header in name.html the drop downs show. Can anyone explain what is happening? name.html {% extends 'fitness/header.html' %} {% block content %} <form method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> {% endblock %} header.html <head> {% load static %} <!-- Prism CSS --> <link href="{% static "tinymce/css/prism.css" %}" rel="stylesheet"> <!-- Compiled and minified CSS --> <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> </head> <body> <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo">Gainz.com</a> <!–– Need to adjust this logo ––> <ul id="nav-mobile" class="right hide-on-med-and-down"> {% if user.is_authenticated %} <li><a href="/profile">profile</a></li> <li><a href="/logout">logout</a></li> <li><a href="/dashboard">dashboard</a></li> <li><a href="/feed">feed</a></li> <li><a href="/forum">forum</a></li> <li><a href="/manual">manual entry</a></li> {% else %} <li><a href="/">Home</a></li> <li><a href="/feed">feed</a></li> <li><a href="/login">login</a></li> <li><a href="/register">register</a></li> {% endif %} </ul> </div> </nav> {% block content %} {% endblock %} </body> <!-- Prism JS --> <script src="{% static "tinymce/js/prism.js" %}"></script> -
Django-Private-Chat in , TemplateDoesNotExist at /dialogs/
Error Image This is the code of my base.html {% comment %} As the developer of this package, don't place anything here if you can help it since this allows developers to have interoperability between your template structure and their own. Example: Developer melding the 2SoD pattern to fit inside with another pattern:: {% extends "base.html" %} {% load static %} <!-- Their site uses old school block layout --> {% block extra_js %} <!-- Your package using 2SoD block layout --> {% block javascript %} <script src="{% static 'js/ninja.js' %}" type="text/javascript"></script> {% endblock javascript %} {% endblock extra_js %}{% endcomment %} This is code of dialogs.html {% extends "base.html" %} {% load static %} {% load i18n %} {% block css %} {{ block.super }} <link href="{% static 'django_private_chat/css/django_private_chat.css' %}" rel="stylesheet" type="text/css" media="all"> {% endblock css %} {% block content %} <input id="owner_username" type="hidden" value="{{ request.user.username }}"> <div class="container"> <div class="col-md-3"> <div class="user-list-div"> <ul> {% for dialog in object_list %} <li> {% if dialog.owner == request.user %} {% with dialog.opponent.username as username %} <a href="{% url 'dialogs_detail' username %}" id="user-{{ username }}" class="btn btn-danger">{% trans "Chat with" %} {{ username }}</a> {% endwith %} {% else %} {% with … -
How Can I Run a Function Inside of Views.py and Print Result? -- Django
The problem is that I am trying to call a function from my views.py and print the result in my template through a context variable. The function prints in the terminal and does not work in the template. I posted a question a few days ago regarding doing this with subprocess, but I still could not figure it out. How can I print "This is a test function for AAPL" in my template instead of in the terminal? Views.py from django.shortcuts import render from backtests.scripts import Backtests def index(request): if 'symbol' in request.GET: symbol = request.GET.get('symbol','Invalid Symbol') request.session['symbol'] = symbol else: symbol = request.session['symbol'] earnings_object = Backtests("AAPL") test = earnings_object.print_discrep() return render(request, 'backtests/earnings.html', {'symbol':symbol, 'test':test}) scripts.py class Backtests: def __init__(self, symbol): self.symbol = symbol def print_discrep(self): print('This is a test function for the graph ' + self.symbol)