Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models/SQL How to determine the wanted "GROUP BY" part of the query?
I have a Django model ProjectName like this: class ProjectName(models.Model): name = models.CharField(_("name"), max_length=255) hasused = models.BooleanField() def __str__(self): return self.name class Meta: managed = False db_table = 'timeentry_project' It is a database view and my goal is to put the most recent projects to the top of the view and get rid of any duplicates in order to be able to provide the queryset to a ModelChoiceField as a parameter. That is also why ProjectName.objects.raw query does not solve the problem. ModelChoiceField does not accept a raw query set. That is also why I cannot use a set containing duplicates. The current situation is that I have the following queryset (Django queryset for that is OK) content: ID Name hasbeenused 81 Mossefixaus 1 80 Ladojen korjaus 0 81 Mossefixaus 0 82 Wartburg autojen koneremontit 0 The boolean value in a 'hasbeenused' column tells has the project been dealt with before or not. The used ones should be on the top of the list. The problem is that I cannot create a Django query that would produce the correct resultset that would be: ID Name max 81 Mossefixaus 1 80 Ladojen korjaus 0 82 Wartburg autojen koneremontit 0 The following … -
Comparing dates using a comparator inside Django template
I am trying to compare the end date of an event with today's date to see if the event has ended. If the event has ended, the website user would not have a button to enrol and if the event has not started or is ongoing, the user would have a button to enrol in html. I have tried this in my html template: {% if event.end_date|date:"jS F Y H:i" <= today|date:"jS F Y H:i" %} {% include 'event/includes/enroll.html' %} But the button shows whether or not the event has ended already. I wanted to add a method in my django model like this: @property def is_today(self): return self.datefinish == datetime.today().date() But I am not sure how to import the method and use it in html template then. I wanted to try to add a variable in my view like this: (Django - Checking datetime in an 'if' statement) is_today = model.end_date >= datetime.today() return render_to_response('template.html', {'is_today': is_today}) But a colleague has written a Class-based view to render the template and not sure how to add the variable to render using the class-based view. I also got an error: TypeError: '>=' not supported between instances of 'DeferredAttribute' and 'datetime.datetime' If … -
Django : NameError: name 'UserAdmin' is not defined [closed]
could you kindly help me on this one please. I just followed the code on the tutorial that I am watching and yet there's an error showed. (NameError: name 'UserAdmin' is not defined) Here's the code: admin.py from django.contrib import admin from .models import User class UserAdmin(admin.ModelAdmin): list_display = ['user_fname', 'user_lname', 'user_email', 'user_position'] admin.site.register(User, UserAdmin) models.py class User(models.Model): user_fname = models.CharField(max_length=200, verbose_name='First Name') user_lname = models.CharField(max_length=200, verbose_name='Last Name') user_email = models.EmailField( unique=True, max_length=200, verbose_name='Email') user_position = models.CharField(max_length=200, verbose_name='Position') pub_date = models.DateField(default=now) def __str__(self): return self.user_email -
Django: How to import a string variable into the django settings file from a middleware
I have a variable in my settings file, SITE_HOST_NAME, that I would want to dynamically change and update according to the current tenant domain, say, t1.leap.com. I have written a custom middleware that fetches the current tenant domain, the problem is appending the current tenant domain it generates to the settings file variable that is currently an empty string. nb: I am implementing multitenancy using Django tenants. settings.py SITE_HOST_SCHEMA = os.getenv('SITE_HOST_SCHEMA', 'http') SITE_HOST_NAME = '' SITE_HOST_PORT = os.getenv('SITE_HOST_PORT', 8000) _default_siteurl = "%s://%s:%s/" % (SITE_HOST_SCHEMA, SITE_HOST_NAME, SITE_HOST_PORT) if SITE_HOST_PORT else "%s://%s/" % ( SITE_HOST_SCHEMA, SITE_HOST_NAME) SITEURL = os.getenv('SITEURL', _default_siteurl) my_middleware.py from django.conf import settings from django.db import connection from django.utils.deprecation import MiddlewareMixin as MIDDLEWARE_MIXIN from django_tenants.utils import remove_www, get_tenant_model, get_public_schema_name from customers.models import Domain class CustomTenantMiddleware(MIDDLEWARE_MIXIN): def get_tenant(self, model, hostname, request): return model.objects.get(domain_url=hostname) def hostname_from_request(self, request): """ Extracts hostname from request. Used for custom requests filtering. By default removes the request's port and common prefixes. """ return remove_www(request.get_host().split(':')[0]).lower() def process_request(self, request): try: hostname = self.hostname_from_request(request) s = Domain.objects.get(domain=hostname) if s: settings.SITE_HOST_NAME = s.domain print(settings.SITE_HOST_NAME) except KeyError: pass # use default urlconf (settings.ROOT_URLCONF) -
Passing JSON data to React component
I am trying to develop an "Yahoo Finance"-style app using Django and React. The dashboard view creates the the JSON data for the users portfolio, and then passes it in the context to the html template, where I would like to use it to create React components. The JSON output for example, is as follows: {'PENN': {'name': 'Penn National Gaming, Inc', 'price': '56.5900'}, 'WMT': {'name': 'Walmart Inc', 'price': '140.0400'}} views.py: def dashboard(request): user = Profile.objects.get(user=request.user) positions = user.positions.all() data_response = {} for position in positions: position_data = {} response = requests.get("https://www.alphavantage.co/query?function=OVERVIEW", params={"symbol": position.symbol, "apikey": key}) data = response.json() name = data["Name"] position_data["name"] = name response = requests.get("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY", params={"symbol": position.symbol, "apikey": key}) data = response.json() price = data["Time Series (Daily)"]["2020-10-28"]["4. close"] position_data["price"] = price data_response[position.symbol] = position_data print(data_response) return render (request, "holdings/dashboard.html", { 'data_response': data_response }) dashboard.html: <div id="app" /> <script type="text/babel"> class App extends React.Component { render() { return ( <UserPosition data={{ data_response }} /> ); } } class UserPosition extends React.Component { render() { return ( ); } } ReactDOM.render(<App />, document.querySelector("#app")); </script> Additionally, I would appreciate any input on whether these API requests should be made server-side or client-side, before I get too deep into the project. -
Implementing Search Form with Django
Hello Stackoverflow community, I am having trouble with my form not rendering in Django. Here's my attempt to render an empty form in views.py. class SearchSite(forms.Form): query = forms.CharField(label="New Item", help_text="Search for any article located on the site.") def search(request): form = SearchSite() context = { "form": form, "query_matches": query_matches } response = render(request, "encyclopedia/layout.html", context) return response Here's what my urls.py file looks like: urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:page_title>", views.page, name="wiki"), path("wiki/", views.search, name="site_search") ] My layout.html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'site_search' %}" method="get"> {% csrf_token %} There should be something here {{ form }} <input type="submit"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> Create New Page </div> <div> Random Page </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> </body> </html> I have noticed two particular problems in above screenshot. Firstly, my form does not render when inside my index.html webpage, which extends layout.html. Secondly, when … -
Can Django changes model instance status when transaction.atomic rolled back?
I want order changes status when raising exception in transaction.atomic block. Does the following code work? try: with transaction.atomic(): order = Order.objects.create( status='PAYING' ) except Exception as e: order.status = 'FALIED' order.save() -
'OrderSerializers' object is not callable
Something is wrong, i try get data values in Order Model, Order Item The relationship Order and OrderItem is Many to Many The relationship Product and OrderItem is Many to Many I try read the docs about Serializer relations link docs But i always see error object is not callable in link api for Order and OrderItem. Help me to solve problem Thanks you everyone class ProductSerializers(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='api:product-detail',lookup_field='slug') class Meta: model = Product fields = ('id', 'title', 'price','slug','category','describe','url') class OrderItemSerializers(serializers.ModelSerializer): tracks = ProductSerializers(many=True, read_only=True) class Meta: model = OrderItem fields = ('user', 'quantity','item', 'tracks') class OrderSerializers(serializers.ModelSerializer): tracks = OrderItemSerializers(many=True, read_only=True) class Meta: model = Order fields = ('user','ordered_date','items', 'tracks') -
How to display a spinner(loader) while downloading the file from django view
How to display a spinner/loader until file downloading in django view <button type="submit" class="buttons">Download</button> def some view(request): with fs.open("filename.pdf") as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=filename.pdf" return response -
Error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name
I have a strange error. I check my code over and over and can't seems to find the error. I write login function, works just fine, added logout function, works fine too. But when I tried to run the basic url, where I should go to the home page (http://192.168.2.80:8000/), it gives me this error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. I added decorators too, to restrict the pages, but can' understand why is the error. viwes.py: @login_required def index(request): return render(request, 'dashboard.html') def loginPage(request): form = AuthenticationForm() if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) if request.GET.get('next'): return redirect(request.GET.get('next')) else: return redirect('feedback:index') return render(request, 'login.html', {'form': form}) urls.py app_name = 'feedback' urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('', views.index, name="index"), ] the root urls.py: app_name = 'feedback' urlpatterns = [ path('admin/', admin.site.urls), path('', include('feedback.urls')), ] I also added these lines into my settings.py: LOGIN_URL = "login" LOGOUT_REDIRECT_URL = '/admin/' Anyone can see what I'm missing? -
Count on big Django Datas
I have a LogTable with about 500k entries per week. models.py class Log(models.Model): timestamp= models.DateTimeField() name = models.CharField(max_length=30) status = models.PositiveIntegerField() objects = LogManager() I want to group the entries by the timestamp and get the counted numbers of each status per timestamp back. Like this: timestamp | automated | offline | user | inactive 29.10.20 17:40 | 5 | 40 | 30 | 15 29.10.20 17:45 | 10 | .... I tried this with a Manager like this: class LogManager(models.Manager): def auto(self, timestamp): return self.filter(datetime__exact=timestamp).filter(status__exact=0).count() def inactive(self, timestamp): return self.filter(datetime__exact=timestamp).filter(status__exact=1).count() def offline(self, timestamp): return self.filter(datetime__exact=timestamp).filter(status__exact=2).count() def user(self, timestamp): return self.filter(datetime__exact=timestamp).filter(status__exact=3).count() def activity(self, timestamp): data = { 'timestamp': timestamp, 'auto' : self.auto(timestamp), 'inactive' : self.inactive(timestamp), 'offline': self.offline(timestamp), 'user': self.user(timestamp), } return data def activity_sum(self): obj = self.values_list('datetime', flat=True) data = {} for i, time in enumerate(obj): data[i] = self.activity(time) return data But this can't be the way because it lasts about 10 minutes to calculate the results if I call Log.objects.activity_sum(). I feel like there is a simple answer but I just can't find it. Thanks for helping me out. -
django.db.migrations.exceptions.NodeNotFoundError: upon running "python manage.py migrate"
I have just started a new django project, which is my own blog. I ran this command first: django-admin startproject mysite Then: python manage.py migrate But, upon running python manage.py migrate, I am getting this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 86, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0012_user_following dependencies reference nonexistent parent node ('account', '0002_contact') I … -
socket.io-stream in django (channels)
I have a server which is used to download files. The server is written in nodejs and looks like this: const express = require("express"); const http = require("http"); const socketIO = require("socket.io"); const ss = require("socket.io-stream"); const port = 4001; const index = require("./routes/index"); const fs = require("fs"); var cors = require('cors') const app = express(); app.use(cors()); app.use(index); const server = http.createServer(app); const io = socketIO(server); io.on("connection", (socket) => { console.log("New Client Connected"); socket.on("download", (fileName) => { startStream(socket)(fileName); }); socket.on("disconnect", () => { console.log("Client disconnected"); }); }); const startStream = socket => fileName => { const file = `${__dirname}/public/${fileName}`; var stream = ss.createStream({allowHalfOpen: true}); const { size } = fs.statSync(file); ss(socket).emit("filedownload", stream, {size} ); var myFileStream = fs.createReadStream(file); myFileStream.pipe(stream); } server.listen(port, () => console.log(`Listening on port ${port}`)); It works great, but the problem is that it needs to be rewritten to Django - which is why i was looking at django channels. ' However I am not sure if Django channels can actually do something like this? The essential part here is socket.io-stream. How would I go about implementing this in Django Channels? -
How to decode django encoded password string in flutter?
i am making application, which has profile screen and in which i am showing password but the password i am getting from a django api is encoded by default now how can i decode my password in flutter application to show the actual password of that user not encoded string. Can anyone help me in this. Note: Django uses the PBKDF2 algorithm with a SHA256 hash to encode passwords -
Will my mail passowrd be visible in console if i use django mail service
I am using Djanog's mail service to send responce mails but i am worried that as i have written my password in my settings.py file so will it be visible to others once i deploy the site as people can see code in console by clicking inspect on websites , Please tell -
How to build a blog recommendation system in python for django?
class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') avatar = models.FileField(upload_to='media/%Y%m%d/', blank=True) body = RichTextField(blank=True ,null=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') likes = models.PositiveIntegerField(default=0) like = models.ManyToManyField(User,related_name='blog_post') dislike = models.ManyToManyField(User,related_name='blog_post_dislike') total_views =models.PositiveIntegerField(default=0) And for user model I used default Django model I want to build a blog recommendation system based on the user profiles and user like dislike and views. -
I am making web based blood donation project in python django .when i run i am dont get option of different blood group. How to resolve this
[Its shows my model.py code and homepage code] Please tell me if there is any module to install so that I get blood group in my project. or any code to resolve this issue -
python manage.py makemigrations Error and django.db.utils.OperationalError Could not connect to server
I am not sure how to fix this issue I have no idea why I am getting this error when I try to python manage.py makemigrations Error: (myproject) D:\E\Project\Trials\Book inventory Assignment>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\core\management\base.py", line 323, in run_from_argvThe above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Krishna Veer Singh\Envs\myproject\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File … -
The below code is not able to save the entered data in database in django
views.py def contact_us(request): if request.method == 'POST': formq = forms.querys(request.POST) if formq.is_valid(): obj = query() obj.name = formq.cleaned_data['your_name'] obj.email = formq.cleaned_data['your_email'] obj.message = formq.cleaned_data['your_message'] obj.save() return redirect(index) else : formq = forms.querys() return render(request, 'home/contact_us.html', {'formq': formq}) models.py class query(models.Model): Name = models.CharField(max_length=200) Email = models.CharField(max_length = 200) Message = models.CharField(max_length=1500) def __str__(self): return self.Name forms.py class querys(forms.ModelForm): class Meta: model=models.query fields = ['Name', 'Email','Message'] Please Help with how can I add the query in the database and view it on the admin page. -
How to get file location path in python, django?
file = request.FILES['file] Here I want to get the path of the selected file. Anyone tell me how to get? Thanks in advance. -
How to download a file using default_storage class in django
I am using django default storage api to save my media files. I am able to save the file open the file for writing. But not able to download the file Used below code to save the file ''' default_storage.save(filename, ContentFile(str(a).encode())) ''' is there any way to download the file in the same way -
Stuck in using intro.js with Sticky CSS style
I use intro.js to help user know how to use the Django website. The intro.js is used on the header bar which help describes the meaning of options. The header bar use the sticky CSS style. The code is as follows: <script> $("#help").click(function (e) { e.preventDefault(); introJs().start(); }); </script> <style> div.sticky { position: sticky ; /* position: -webkit-sticky; */ width: 100%; top: 0px; background-color: #96C9DB; margin-bottom: 30px; padding-bottom: 40px; z-index: 9999; } </style> <div class="sticky"> <div class="dropdown" style="float: right; margin: 0px 10px;"> {% if request.user.is_authenticated %} <a href="{% url documention' %}">Documention</a> <a href="{% url 'reset_pw' %}">Reset Password</a> <a href="" id="help">Help</a> <a href="{% url 'logout' %}">Logout</a> {% endif %} </div> <div class="header-bar"> <a href="{% url 'aaa_home' %}" data-intro="this is AAA" data-step="1">AAA</a> <a href="{% url 'bbb_home' %}" data-intro="this is BBB" data-step="2">BBB</a> <a href="{% url 'ccc_home' %}" data-intro="this is CCC" data-step="3">CCC</a> </div> </div> {% block content %}{% endblock %} If the attribute for the position is "sticky", then text will be covered as follows: Picture 2: https://ppt.cc/fw21ax If the attribute for the position is "-webkit-sticky", then words will can be displayed, but the header bar will not fix at the top: My goal is to fix the header bar at the top and … -
How to redirect to other url after downloading a file attachment in django
The file which I have generated in django view, after downloading this attachment I need to redirect to other url. Please someone suggest me how to achieve this or any other method to download file attachment without return response in django view def some view(request): with fs.open("filename.pdf") as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=filename.pdf" return response # Here I need to redirect to other page -
Wagtail and Django-fobi: TemplateDoesNotExist at /test-form/ page/base.html
django/wagtail noob here, i go ok writing basic stuff from scratch, but sometimes stumble when trying to integrate or modify other packages. using wagtail==2.10.2 and django-fobi==0.16.4, ive installed fobi as per instructions, and created a fobi form and added it to a wagtail page. When i go to view the page, i get "TemplateDoesNotExist at /test-form/" "page/base.html" so it's looking for base.html in 'page', but there is no folder/app named page?? is page part of wagtail core? do i have to extend class FobiFormPage(AbstractFobiFormPage), or should it just work out of the box? -
How can i fix migration problem in my Django project?
I have a migration problem: This is forms.py file enter image description here this is models.py enter image description here this is admin.py enter image description here