Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'my_app’, app already in INSTALLED_APPS
I’m trying to deploy my Django app through Heroku but I’m getting a ModuleNotFound error after running a production environment with gunicorn wsgi path. My app is included in settings.py and it was working fine while in the development environment. But now I’m getting errors for deployment. I have problems with how my project is structured, thus Procfile does not leave in the same directory as manage.py, and I believe this could be the issue. Any hint or help is more than appreciated. Directory structure >FINALPROJECT(root) > .vscode > project5 > brainSkills > migrations > static > templates apps.py models.py urls.py views.py > project5 _init_.py settings.py wsgi.py _init_.py manage.py > venv .env .gitignore Procfile README.md requirements.txt Procfile web: gunicorn project5.project5.wsgi wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project5.project5.settings') application = get_wsgi_application() setting.py import os from pathlib import Path from dotenv import load_dotenv INSTALLED_APPS = [ 'brainSkills', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ROOT_URLCONF = 'project5.urls' WSGI_APPLICATION = 'project5.wsgi.application' Error after gunicorn project5.project5.wsgi or Heroku local 5:32:28 PM web.1 | File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module 5:32:28 PM web.1 | return _bootstrap._gcd_import(name[level:], package, level) 5:32:28 PM web.1 | File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 5:32:28 PM web.1 | … -
Requests is not working in one of my DJANGO project
I am having trouble with requests package and I tried my best to resolve this problem. Problem- requests is not working in one of my Django Projects. It returns 403 Forbidden. But the same code is working on my other Django Project (Same laptop with same internet connection, but different virtual environment). So, because of this I am not able to use requests package in one of my existing Django Project. Here is the code: This is the demo code which I will run on two Django Project with two different virtual environment. import requests from bs4 import BeautifulSoup from django.shortcuts import render # from .models import RequestData def home(request): data = [] urls = [ "https://api.github.com/search/repositories", "https://www.dataquest.io", "https://www.python.org", "https://api.github.com/events" ] for url in urls: r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') if soup.title: data.append(str(soup.title)) else: data.append("No Title") return render(request, "requester/index.html", {'data': data}) Here is my HTML part: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% for dat in data %} <li>{{dat}}</li> {% endfor %} </body> </html> Here are my responses from both the Django project. First (Which have problem) Second(Without any problem) Also, I tried with different versions of … -
How to use TabularInline in Django E-commerce Project
I am trying to show the orderitemsadmin in the orderadmin using TabularInline but I keep getting different errors like the following error. AttributeError: 'OrderItemAdmin' object has no attribute 'urls' and django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed This is a Django e-commerce project and I am trying to facilitating the admin viewing the orders and their items. I don't have much experience in using TabularInline that is why I am not able to do it corrrectly or what might be the mistake that I am doing. Here is the admin.py class OrderItemAdmin(admin.TabularInline): list_display = ['item', 'quantity', 'ordered'] model = OrderItem raw_id_fields = ['item'] class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'status', 'refund_requested', 'refund_granted', 'ref_code'] inlines = [ OrderItemAdmin, ] admin.site.register(OrderItem, OrderItemAdmin) admin.site.register(Order, OrderAdmin) Here is the models.py class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) -
How to paginate Django Admin for Order Model
In my E-commerce Project, Everytime I click on the orders model in Django Admin, it takes a while to load, so I thought the reason might be because of the many orders in the page which is not paginated. So my question is how to paginate the order.model in Django Admin, second is this the reason why it is the only page that is taking a while to load or might there be another reason that I should be thinking of? Here is the models.py class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, unique=True, blank=True, null=True) items = models.ManyToManyField(OrderItem) --------------------------------------- Here is the admin.py class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'status', 'refund_requested', 'refund_granted', 'ref_code'] list_display_links = [ 'id', ] list_editable = ['status'] list_filter = ['ordered', 'ordered_date', 'refund_requested', 'refund_granted', 'status'] search_fields = [ 'user__username', 'ref_code' ] actions = [make_refund_accepted] -
How to Paginate a Django View inside a loop
I was looking into the pagination offered by Django 3.0, and I was wondering how to implement pagination from inside a loop. For example, take this snippet where I retrieve a collection of images based on some selected categories and display the images. There are ~800 images per category, and 12 categories. What I would like to have is the category name at the top of the page, 20 or so images, the the page indicators. class MyPage(View): def get(self, request): q_dict = request.GET sets = [] # the full data set to display on the page - a list of dictionaries for category in categories: document_ids = list(DocumentMetaData.objects.filter(metadata__has_key=category).values('document_id', flat=True)) images = [] for doc_id in document_ids: image = DocumentImage.objects.get(document=doc_id) params = {'ID': doc_id, 'Category': category} detail_url = encode_urls('details.html', params) urls = {'image_url': image.xsmall_file.url, 'detail_url': detail_url} images.append(urls) # the dictionary contains the data to display on the page sets.append({'header': category.name, 'images': images, }) paginator = Paginator(sets, 20) # 20 images in each page if 'page' in q_dict: page = q_dict['page'] else: page = 1 try: page_obj = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page page_obj = paginator.page(1) except EmptyPage: # If page is … -
Django | CSRF Verification Failed
I'm building a Django powered blog-like app for practice and learning. I'm working on setting up a form for users to leave comments on posts. I have a Post model that takes in a User foreign key, and a Comment model that takes in a User foreign key and a Post foreign key (to identify the post the comment is tied to). I know the way I have it setup is not yet functional, but I'm just trying to debug a CSRF issue I keep having. Here's my code: models.py class Comment(models.Model): date_posted = models.DateTimeField(default=timezone.now) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) views.py @login_required def post_detail(request, post_id): if request.method == 'POST': print("posted") return redirect('Home') else: comment_form = CommentForm() context = { 'post': Post.objects.get(id=post_id), 'comments': Comment.objects.order_by('date_posted'), 'comment_form': comment_form } return render(request, 'feed/postdetail.html', context) template, "postdetail.html" <form method="POST" enctype="text/plain"> <div class=comment-line> {% csrf_token %} {{ comment_form }} <button type="submit">Post</button> </div> </form> And I DO have the following in my middleware 'django.middleware.csrf.CsrfViewMiddleware', I keep getting an error stating, "CSRF verification failed. Request aborted" for the reason "CSRF token missing or incorrect." This only happens when I click the post button. I'm only just learning Django, what am I doing … -
Is there a way to connect a model object with another object?
So i have a problem where I have two models; ORDER and ORDERITEM, as seen before class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) post = models.ForeignKey('blog.Post', on_delete=models.SET_NULL, blank=True, null=True) #post = models.ForeignKey('OrderItem', related_name='oi', on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) qr_code = models.ImageField(upload_to='qrcode', blank=True) def __str__(self): return str(self.transaction_id) class OrderItem(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.post.title This is how it works, when a user makes an order it goes to the orderitem, when its order is completed, it goes to Order model, now, i want to be able to get the Post the user purchased from Order (not Orderitem) Model, i can get it from OrderItem, because presently with the code abov Order models does not show the particular post purchased, it just shows a list of all the posts. I really need to get the Post purchased from Order because im building a notification system using signals and it has to be from Order (which is created when the user FINISHES the process of making an order). I hope you get me, … -
Docker and Django – keep everything up to date & secure
I am new to Docker and begin to understand how that whole thing works. My final goal is to deploy my Django project (which at the moment is running locally) to Google Code Run or a similar service, but there is still a way to go. Actually, thanks to this book, I already got my project running within a Docker container locally on my Mac, which is great. My Dockerfile starts with FROM python:3.8 and contains COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system So every time I build my container, updates wich are available for Linux, Python, Django and other packages I am using are included automatically, I guess (unless I declare otherwise e.g. for packages in my Pipfile). The idea is to develop the app locally and test everything using Docker on my Mac. When it comes to updates, I have to check if everything is still consistent. If everything works fine locally, I (later) can deploy the container to somewhere else and everything should be fine. Am I basically right or did I miss something important? -
URL parameters don't select designated options in select2 drop-down
I have created URL parameters on my site. For example, I have multiple custom widgets including a calendar, toggle switches, and more. My question is when I access a certain URL with my parameters I get the right plot/graph, but the options selected in my drop-down won't get selected? The parameters get applied to all my other widgets, but my select2 drop-down. It definitely takes in the right options selected, but won't display to let the user know the parameters passed were successful. I hope I am making sense, but to sum it all up when I pass my desired parameters my site will load as expected. However, the options will not get selected and display to the user. The URL parameters were created using a GET request. Here's my js file $(document).ready(() => { $.fn.select2.amd.require([ 'select2/utils', 'select2/dropdown', 'select2/dropdown/attachBody' ], function (Utils, Dropdown, AttachBody) { function SelectAll() { } SelectAll.prototype.render = function (decorated) { var $rendered = decorated.call(this); var self = this; //define the buttons inside the menu var $selectAll = $('<input type="checkbox"> Select/Unselect All</input>' ); //append the buttons inside the menu $rendered.find('.select2-dropdown').prepend($selectAll); // Pass in an array to our value to select all. // Check if checkbox has been … -
The 'Access-Control-Allow-Origin' is not included on response header for images
I'm developing a simple web app, using Nuxt for the frontend and Django for the backend. The Django API has 2 endpoints, tag and product, and in the product endpoint there's a image_url value, which contains the link to a JPEG file, stored in a Django server sub-directory called media. Since both apps are being served on different ports (frontend in 3000; backend in 8000), I needed install the CORS headers package for django, and I configured it like this (on settings.py): CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ( '<my-host>:3000', '<my-host>', ) CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) CORS_ORIGIN_WHITELIST = [ 'http://<my-host>:3000', ] Then, on the frontend, I use axios for the HTTP request. The strange thing (at least for me) is that the CORS headers are included in every request made to the API, but not on the images. So, with an HTTP request for http://<my-host>:8000/product/1, the response includes (among other things) this: { "id": 1, "image_url": "http://<my-host>/media/images/1/20200916113917386794.jpg" ... } By examining the Network tab, on Chrome's DevTools, I see the following response headers from http://<my-host>:8000/product/1: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://192.168.33.11:3000 … -
Querying related model-attributes in django
I have the following custom user model arrangement. ``` class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class StudentProfile(models.Model): student = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) location = models.CharField(max_length=8, blank=False, default='') class TeacherProfile(models.Model): teacher = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) gender = models.CharField(max_length=8, choices=GENDER_CHOICES, default='') ``` I am able to a query the students based on the location of their teacher (current user). Student.objects.filter(location=request.user.teacher.location) I can also query the user model & find all teachers/students User.objects.filter(is_teacher=True) QUESTION: Without relying on the profile models (Student & Teacher) How can I extend the query on abstractuser using profile attributes. [X]-This is wrong but the idea is something like; User.objects.filter(is_teacher=True).filter(is_teacher.location=newyork) -
Python job matching query does not exist with get_previous_by_start_dt
We are seeing the error Job.DoesNotExist: Job matching query does not exist and normally I would know what to do, only this time we are using a native method # get previous job for the same brand def previous_job(self): return self.get_previous_by_start_dt(brand=self.brand, status='finished') or None I was reading this for an asnwer but no success: Django error - matching query does not exist question: how do I implement the same error free logic with try/catch or some other method for get_previous_by_start_dt? File "/var/www/html/shirts/scrapy/sohb2bcrawlers/db_tool/db_app/models.py", line 75, in previous_job return self.get_previous_by_start_dt(brand=self.brand, status='finished') or None File "/usr/lib/python3.6/site-packages/django/db/models/base.py", line 960, in _get_next_or_previous_by_FIELD raise self.DoesNotExist("%s matching query does not exist." % self.class._meta.object_name) db_app.models.Job.DoesNotExist: Job matching query does not exist. -
Django deployment variables
I have a development app running locally. I have a production app running on my server. I would like to keep developing locally and push my changes. However, the dev version uses local postgres and the static and media files reside inside the project. The server version the static and media files are in a static public_html directory served by apache. Can I have a local static and media files as well as different postgres credentials on localhost than on the server? How do I accomplish that? -
Why my response data is not being shown in the postman and how do I see the request data in Django
views.py from django.shortcuts import render from rest_framework import viewsets from django.http import HttpResponse from .serializers import TodoSerializer from .serializers import UserSerializer from .models import Todo from .models import User class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer queryset = Todo.objects.all() def get_object(request): return "Added"; class UserView(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() def get_object(request): print("request", request) return "Registered"; class LoginView(viewsets.ModelViewSet): #serializer_class = UserSerializer #queryset = User.objects.all() #print("queryset = ",queryset[len(queryset)-1].email_id) #print("serializer_class = ",serializer_class) def get_object(self,request): return HttpResponse("request") # Create your views here. urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers from todo import views router = routers.DefaultRouter() router.register(r'users', views.UserView) router.register(r'todos', views.TodoView) router.register(r'login', views.LoginView) print("In url file") urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ] This is my views.py file and urls.py file. I have a model created for user, with fields- email_id and password CRUD operations are implemented automatically, so how do I validate data passed from the login form in frontend Please tell me what's wrong in the code. I am not able to do the login part. -
Django default cache not used
I have this lines in Django settings: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.environ["REDIS_URL"], # I tried hard-coding this value as well "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, } } Then I do: python3 manage.py shell >>> from django.core.cache import caches >>> caches["default"] >>> <django_redis.cache.RedisCache object at 0x7f87a61eb730> Cash uses Redis fine, but if I do: >>> from django.core.cache import cache >>> cache <django.core.cache.DefaultCacheProxy object at 0x7f7773164dc0> As you can see, it's not Redis, I checked that it has separate storage, each process has separate cache. Why is it so? Shouldn't from django.core.cache import cache use Redis as cache? I checked many times, "default" not misspelled. -
Issues sending email with django-recpatcha and django-crispy-forms
I'm trying to set up a Contact Form on a client website using the django-recaptcha app and django-crispy-forms. My form data isn't passing is_valid() on POST and I can't figure it out. Any help would be greatly appreciated! (Running Django 3.11 on Windows 10 with Python 3.8.5.) As far as I know, I've set all the configs up according to spec. Here's the models.py: from django.db import models class ContactEmail(models.Model): created = models.DateTimeField(auto_now_add=True) first_name = models.CharField(blank=False, max_length=50) last_name = models.CharField(blank=False, max_length=50) email = models.EmailField(blank=False) phone = models.CharField(max_length=32, blank=True) subject = models.CharField(blank=False, max_length=80) message = models.TextField(blank=False) def __str__(self): return "{} {}: {} ({})".format( self.first_name, self.last_name, self.subject, self.created.strftime("%m/%d/%Y, %H:%M:%S UTC") ) forms.py: from django import forms from django.urls import reverse from .models import ContactEmail from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV3 from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class ContactForm(forms.ModelForm): captcha = ReCaptchaField(widget=ReCaptchaV3(attrs={ 'data-theme': 'dark', 'data-size': 'compact' })) class Meta: model = ContactEmail fields = [ 'first_name', 'last_name', 'email', 'phone', 'subject', 'message', ] def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['captcha'].label = False self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit', css_class='btn-block')) self.helper.form_method = 'POST' self.helper.form_action = reverse('contact') views.py: import datetime from django.contrib import messages from django.core.mail import send_mail from django.http import HttpResponse … -
Django "Exception has occurred: ImproperlyConfigured Requested setting DEBUG, but settings are not configured..." even after setting in manage.py
Sorry, I am a newbie in Django, so please comment if I have forgotten any important information. I have set up my Django App following this VSCode tutorial. In short, it teaches me to build a docker image of a Django App in Venv. When I started to run with VSCode, an error occurred saying that Exception has occurred: ImproperlyConfigured Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.. However, I have os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yiweis_blog.settings') in my both wsgi.py and manage.py. Meanwhile, when I attach a shell directly to the container, and run python manage.py runserver, it prints Django version 3.1.1, using settings 'yiweis_blog.settings'. I have also tried to assign variable yiweis_blog.settings to DJANGO_SETTINGS_MODULE in dockerfile and export the variable in terminal, but both of them still did not work. Any help is appreciated. Thanks! -
I can't render the image template tag from my Wagtail page model
I'm trying to access an image, feed_image on a blog post page's template but am unable to render it correctly. I have tried passing it specifically to my context variables, calling it directly, through the page.notation, and through wagtail's own {% image %} template function. models.py {BlogPage} class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) quote = models.CharField(max_length=250, default='', blank=True) author = models.ForeignKey('blog.Author', null=True, on_delete=models.SET_NULL) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name='+' ) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple) ] promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ] content_panels = Page.content_panels + [ ImageChooserPanel('feed_image'), FieldPanel('date'), FieldPanel('intro'), FieldPanel('body', classname="full"), FieldPanel('quote'), FieldPanel('author') ] parent_page_types = ['blog.BlogIndexPage'] @property def parent_page(self): return self.get_parent().specific def get_context(self, request, *args, **kwargs): context = super(BlogPage, self).get_context(request, *args, **kwargs) context['parent_page'] = self.parent_page context['feed_image'] = self.feed_image context['all_categories'] = BlogCategory.objects.all() return context blogpage.html {% extends "base.html" %} {% load static %} {% load wagtailcore_tags %} {% load wagtailimages_tags %} {% comment %} {% load custom_tags %} {% endcomment %} {% block content %} <section class="blog-post-header" style="background-image: url({{ page.feed_image.url }})"> <div class="container h-100 align-items-center"> <div class="row h-100 align-self-center"> <div class="col my-auto text-center mh-100"> <h2 class="curly text-vivid-green display-4 font-weight-bold">{{ … -
How to post OneToOne field in django rest-framework using overwrite create method
I am trying to override create method to make a post request but i am stuck, here is my code class Order(models.Model): street_number = models.PositiveIntegerField(blank=True, null=True) street_name = models.CharField(max_length=250, null=True, blank=True) class Seller(models.Model): order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='seller_order',blank=True, null=True) first_name = models.CharField(max_length=250, null=True, blank=True) last_name = models.CharField(max_length=250, null=True, blank=True) class OrderSerializer(serializers.ModelSerializer): sellers = SellerSerializer() class Meta: model = Order fields = '__all__' def create(self, validated_data): order = Order.objects.create(**validated_data) seller_validated_data = validated_data.pop('sellers') if seller_validated_data: seller_obj = Seller.objects.create(order=order) seller_obj.first_name = seller_validated_data.get('first_name') seller_obj.middle_name = seller_validated_data.get('middle_name') seller_obj.last_name = seller_validated_data.get('last_name') order.save() return order My json in postman i am sending like below { "street_number":11, "street_name":"dfd", "seller":{ "first_name":"kk", "last_name":"dfdf" } } But i am unable to create seller object with a relation of order, please help me -
Django delivery form
I am building an e-commerce website and at the checkout want the user to fill out delivery form (with address, zip, city etc.). I have made the form in Django, however the delivery works only in certain region and I want to accept addresses in this region. Otherwise, I want user to see that delivery doesn't work in his region. How could I do it? Did anyone face this problem? -
Npm package in Django isn't working on Heroku
I installed a package using npm in my Django app and then moved the folder to my static folder and imported it to base.html with <script src="/static/js/convertapi-js/lib/convertapi.js"></script> This works fine on localhost but when I deploy the app to Heroku it can't find the file. I'm new to Django so any help would be appreciated. -
Ordering Django Chained Queryset
I have a search page which pulls a request from several models and compiles them into separate querysets which are then combined using the chain() function before being rendered to the template. The views.py file looks like this: class SearchResults(ListView): template_name = 'front_end/search_page.html' context_object_name = 'query' def get_queryset(self): query_param = self.request.GET['q'] film_search = Film.objects.filter(Q(title__icontains=query_param)).distinct().order_by('-gross') actor_search = Actor.objects.filter(Q(name__icontains=query_param)).distinct().order_by('-career_gross') director_search = Director.objects.filter(Q(name__icontains=query_param)).distinct().order_by('-career_gross') writer_search = Writer.objects.filter(Q(name__icontains=query_param)).distinct().order_by('-career_gross') return list(chain(film_search, actor_search, director_search, writer_search)) This code works but I want to order the final list by 'career_gross' and 'gross' with the instance with the largest value for either of those attributes appearing first in the list. This is a problem as the querysets come from different models - I cannot order the chained list using order_by('career_gross') like I did before (not to mention not all models have a 'career_gross' attribute). To put it simply, can I order chained querysets by the value of different attributes coming from different model instances. -
Hi am new to Django, i want to get the system user/computer name who is accessing my website on intranet and store the hits into a sqlite DB table
how can I get the system/computer/user name of user who is accessing my website on internal network. I want to record the end user hits and to store them in SQLite DB -
django-import-export empty rows before csv header trigger exception while importing
While importing data from csv, I realized that this error is triggered if the first row is not the header list indices must be integers or slices, not str first_name,last_name,email,password,role Noak,Larrett,nlarrett0@ezinearticles.com,8sh15apPjI,Student Duffie,Milesap,dmilesap1@wikipedia.org,bKNIlIWVfNw,Student It only works if the first row is the header first_name,last_name,email,password,role Noak,Larrett,nlarrett0@ezinearticles.com,8sh15apPjI,Student Duffie,Milesap,dmilesap1@wikipedia.org,bKNIlIWVfNw,Student ... I tried overwriting before_import to remove any blank row def before_import(self, dataset, using_transactions, dry_run, **kwargs): indexes = [] for i in range(0, len(dataset)): row = ''.join(dataset[i]) if row.strip() == '': indexes.append(i) for index in sorted(indexes, reverse=True): del dataset[index] return dataset This works for all the rows, except the first row which should always contain the header, and if not the error is thrown. -
How to use websockets client/server between two Celery tasks?
I use Celery and Redis in my Django application to handle tasks and one of them is to subscribe to a websocket stream to receive financial data in an async loop. Of course others Celery tasks need these informations and I'm trying to figure out how to transmit the data to them. So far I tested writting the stream every x seconds into the database, works but consummes CPU. Not really efficient and cannot be real-time. Another solution could be to update a dictionary when fresh data arrive but unfortunnatly Celery tasks are executed in seprate processes so that global variable from one task isn't accessible in another task. After some research I came to the conclusion that best solution is to use the websockets library and I'm trying to implement this example of a websocket client/server. The idea is to start the ws server in the same task that receive the stream of financial data so it can transmit the data to another 'client' task. To do so I declared a global variable data which contain the stream as it arrives, and it's this variable I would like to transmit to the client in the gretting message. The server …