Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Minimum value of Each Query in Filter
I have two tables 1 product and 2nd price.like this class Activity(models.Model): activityName = models.CharField(max_length=50 , null=False, blank=False) activityId = models.CharField(max_length=20, null=True, blank=True) class PerPersonTire(models.Model): activity = models.ForeignKey(Activity, on_delete=models.CASCADE) name= models.CharField(max_length=100 , null=True , blank=True) minNumerofParticipents = models.IntegerField(default=0) price=models.IntegerField(default=0) Now case is in every activity have many price in foreign key. So when I Query on Activity I need minimum price from that table aswell. like Activity.object.all() I need here minimum price of each activity from price table as well. Any help regarding this would be highly appreciated. -
Django enctype=multipart/form-data on localhost returns white screen
I am running django on a pipenv virtual machine on my MacBook on localhost:8000. I created a django form to upload an image with enctype=multipart/form-data. When clicking on submit, on all browsers, I get a white page. Checking the browsers network status, its a 400 error, and in Firefox I get: The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature. When removing the enctype, everything works fine - but of course the image isn't uploaded. The error seems to occur before any data manipulation on my side. On a remote development server, everything works fine with and without encoding - so it seems to be related to my development environment. Unfortunately I can't find any hints on why this error occurs. Does anybody have a hint or an idea on how to solve this? More Information Macbook Pro Catalina 10.15.3 Django 2.2 Running with the django internal server (manage.py runserver) -
Django Polls App Part 3 Template Syntax Error
I am new to Django and going through the tutorial of polls app. I am stuck on part 3 with Template syntax error. I have searched all related posts on stackoverflow but can not find the problem. Below are my files: Polls/Views.py: from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) Polls/models.py: from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Polls/templates/polls/index.html: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} polls/urls.py: from … -
product weight in ebaysdk
how can i can get product weight ? I used trading api but most of weight of the products equal to 0. is there any way to get product weight all the time? I requested like this: response = api_trading.execute('GetItem' , {"ItemID":"184097524395",'DestinationPostalCode':'2940','DestinationCountryCode':'GB'}) -
Django: Unable to Write File from ModelForm on Apache and Mod_wsgi
I have a Django 3.0.3 site running on RHEL 7 and Apache using mod_wsgi. On my development machine (Windows) I am able to save a file via a FileField field type. However, when deploying on production (RHEL 7 and Apache using mod_wsgi) I get an "[ErrNo 13] Permission denied" error when trying to save the file. I have set folder permissions to drwxrwxrwx. for the MEDIA_ROOT folder for the apache user which is named "apache" in my instance (as confirmed by both calling getpass.getuser() within the program and also from the httpd conf settings. It is also the name listed on mod_wsgi.process_group on the Django debug page. I have included my relevant code and debug: Debug Environment: Request Method: POST Request URL: https://www.samplesite.com/samples/addpatient/ Django Version: 3.0.3 Python Version: 3.7.1 Installed Applications: ['samples.apps.SamplesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'bootstrap3', 'django.contrib.staticfiles', 'notifications'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch … -
Run Django server at Single Host IP address
I am trying to restrict Django server to single Host IP in Local PC. Initially I am running Django server at Host IP lets say 127.0.0.1. Again I am starting server at different Host IP 127.0.0.2 (in same PC) than mentioned in step1. Now I am able to browse my website at both IPs. But I need server should be working at last given host IP i.e 127.0.0.2 and old IP address shouldn't give response to any requests from 127.0.0.1 IP. IP address I have given here is just sample IPs. Note: I will not be restarting the server. -
How does the functionality of a function in has_object_permission differs when both return same Boolean value?
Recently I started to learn about permissions in Django rest framework, and I find below code a bit confusing. class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user I know that has_object_permission is linked to a specific instance and is called from get_object, but I don't know how it works under the hood. I mean if the condition is met, both returns True, but first one is ready-only and second one is update and delete. What puzzled me though is how one gives read-only access and second gives write and delete access under ceiling of same function? Please help me understand this. Thank you. -
Weird behavior in django __date filter
I'm trying to filter the model by date. class Participant(models.Model): email = models.CharField(unique=True, max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email There are 4 entries that were created at date(2020, 3, 28): 2020-03-28 06:28:14.475307+00:00 2020-03-28 06:16:05.312023+00:00 2020-03-28 06:11:27.322146+00:00 2020-03-28 06:03:27.500164+00:00 When I'm doing this: Participant.objects.filter(created_at__gte=datetime.date(2020, 3, 28), created_at__lt=datetime.date(2020, 3, 29)) I'm getting these 4 entries. But, when I'm doing this: Participant.objects.filter(created_at__date=datetime.date(2020, 3, 28)) I'm getting an empty queryset. I have: TIME_ZONE = "UTC" USE_TZ = True I'm in timezone Asia/Kolkata I'm using django version 2.2, Mysql, python version 3.6.7 I have seen this answer: https://stackoverflow.com/a/55608903/5157204 but I'm unable to figure out what the problem is. Can anyone help me figure out the problem? -
Calculate book value of share positions in Django
I'm working on a small project where I want to show a summary of accounts in cash and shares. There is some Python code involved and I want to present the output in a template. I'm trying to calculate the book value of each position of the share portfolio however I’m getting an error and I don’t know what to do. Your help would be much appreciated. model.py class Shares(models.Model): name = models.CharField(max_length=128) ticker = models.CharField(max_length=128) date = models.DateField() quantity = models.FloatField(default=0) price = models.FloatField(default=0) currency = models.CharField(max_length=128) view.py class SharesListView(ListView): model = Shares context_object_name = 'shares_details' def get_context_data(self, **kwargs): context = super(SharesListView, self).get_context_data(**kwargs) latest_fx = fx_table.objects.last() queryset = context['shares_details'].annotate(book_value=Case( When(Q(quantity >0, then=F('price')*('quantity'))), default=Value(0), output_field=FloatField() ) ) context['shares_details'] = queryset context['total_shares'] = queryset.aggregate(sum=Sum('book_value'))['sum'] return context Error details Exception Type:NameError Exception Value:name 'quantity' is not defined Exception Location:...views.py in get_context_data, line 58 Thanks -
Django bootstrap modal not showing
I am trying to show a modal on a button click, however, after I click on the modal it does not show the modal, I do not know what seems to be the issue since I followed the exact tutorial on bootstrap and W3Schools. Here, is my template: {% for comment in comments %} <div class="border-bottom"> <div class="row pt-1 pl-4"> <div class="col-xs"> <img class="img-create-post rounded-circle mr-1" style="width: 2.1rem;height: 2.1rem;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image"> </div> <div class="col-xs" style="margin-bottom: 0;"> <span class="text-dark font-size-smaller" href="#" style="font-weight: 500;">{{ comment.name.first_name }}</span> <span class="text-muted small">•</span> <a class="text-muted small" href="#">@{{ comment.name.username }}</a> <span class="text-muted small">•</span> <span class="text-muted small">{{ comment.get_created_on }}</span> <p class="font-weight-light pl-1">{{ comment.body }}</p> </div> </div> <div class="d-flex justify-content-between"> <div> <span class="text-muted small view-replies">view {{ comment.replies.count }} replies <i class="fas fa-caret-down"></i></span> </div> <div> <!-- button to show modal --> <button class="btn btn-sm small float-right text-muted button-outline-light reply-btn" type="button" data-toggle="modal" data-target="modal-comment-reply">Reply</button> </div> </div> <div class="comment-replies"> {% for reply in comment.replies.all %} <div class="row pt-1 pl-4"> <div class="col-xs"> <img class="img-create-post rounded-circle mr-1" style="width: 2.1rem;height: 2.1rem;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image"> </div> <div class="col-xs" style="margin-bottom: 0;"> <span class="text-dark font-size-smaller" href="#" style="font-weight: 500;">{{ comment.name.first_name }}</span> <span class="text-muted small">•</span> <a class="text-muted small" href="#">@{{ comment.name.username }}</a> <span class="text-muted small">•</span> <span class="text-muted small">{{ comment.get_created_on }}</span> <p … -
How can I pull data from my database using the Django ORM that annotates values for each day?
I have a Django app that is attached to a MySQL database. The database is full of records - several million of them. My models look like this: class LAN(models.Model): ... class Record(models.Model): start_time = models.DateTimeField(...) end_time = models.DateTimeField(...) ip_address = models.CharField(...) LAN = models.ForeignKey(LAN, related_name="records", ...) bytes_downloaded = models.BigIntegerField(...) bytes_uploaded = models.BigIntegerField(...) Each record reflects a window of time, and shows if a particular IP address on particular LAN did any downloading or uploading during that window. What I need to know is this: Given a beginning date, and end date, give me a table of which DAYS a particular LAN had ANY activity (has any records) Ex: Between Jan 1 and Jan 31, tell me which DAYS LAN A had ANY records on them Assume that once in a while, a LAN will shut down for days at a time and have no records or any activity on those days. My Solution: I can do this the slow way by attaching some methods to my LAN model: class LAN(models.Model): ... # Returns True if there are records for the current LAN between 2 given dates # Returns False otherwise def online(self, start, end): criterion1 = Q(start_time__lt=end) criterion2 = … -
Sprinkling VueJs components into Django templates
I'm working on a Django site and I'm looking to "sprinkle" in some Vue components to the Django rendered templates. I'm working in a single repository and have webpack setup to create style/js bundles that I use within the Django templates. I'm struggling to get the functionality working how I'd like it, mainly regarding renderless Vue components, since I want to handle all (or at least the vast majority) of html within the Django templates and just use Vue components for some logic in some places. I'm using some of the advice from here but it didn't quite work as they'd suggested (although that's exactly how i'm hoping it can work) and I feel like I need to take advantage of scoped-slots. I am using the Vue esm distribution to include the Vue compiler. The setup I'm currently using is as follows: // webpack_entrypoint.js import Vue from "vue"; import RenderlessComponent from "./components/RenderlessComponent.vue" // I will also be registering additional components here in future for other pages // and I'm under the impression that doing it this way allows me to reuse the Vue instance // defined below Vue.component("renderless-component", RenderlessComponent) new Vue({ el: "#app" }) // components/RenderlessComponent.vue <template></template> <script> // Other … -
How to store attachement files(image) to remote location?
I am using django-summernote, now i want to change upload location to remote(Another hosting platform) , Please anyone help me. Thanks in advance. -
How to access django tenant_schemas Tenant URL in browser
Good day! I am using django tenant_schemas (https://django-tenant-schemas.readthedocs.io/en/latest/) to develop a SaaS web application. I have created a Tenant with a domain_url but I cannot access it through a web browser. Here is some parts of my settings.py: ALLOWED_HOSTS = ['*'] SHARED_APPS = ( 'tenant_schemas', 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom Apps # Third Party Apps 'corsheaders', 'rest_framework', 'dynamic_preferences', # For Pref # 'api.apps.ApiConfig', 'revproxy', # For Reports 'tenant_schemas', #'taggit', 'taggit_serializer' # For tags - might not use with Vue..) TENANT_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',) INSTALLED_APPS = ( 'tenant_schemas', 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom Apps # Third Party Apps 'corsheaders', 'rest_framework', 'dynamic_preferences', # For Pref 'api.apps.ApiConfig', 'revproxy', # For Reports #'taggit', 'taggit_serializer' # For tags - might not use with Vue.. ) DEFAULT_FILE_STORAGE = 'tenant_schemas.storage.TenantFileSystemStorage' MIDDLEWARE_CLASSES = ( 'tenant_schemas.middleware.TenantMiddleware', # ...) DATABASE_ROUTERS = ( 'tenant_schemas.routers.TenantSyncRouter', ) TENANT_MODEL = "tenant_public.Tenant" # app.Model Created Tenant using python manage.py shell: tenant = Tenant(domain_url='tenant.demo.com', schema_name='tenant1', name='My First Tenant') Save: tenant.save() However, when I run python manage.py runserver and access tenant.demo.com, I get a 404 Not Found response. -
bulk_update: django-field-history vs django-simple-history
I am using Django v3.0.5. I have been using django-simple-history app in my project. It works well. However, I noticed that it doesn't work with bulk_update. This is known / documented (https://django-simple-history.readthedocs.io/en/latest/common_issues.html#bulk-creating-and-queryset-updating): Unlike with bulk_create, queryset updates perform an SQL update query on the queryset, and never return the actual updated objects (which would be necessary for the inserts into the historical table). Thus, we tell you that queryset updates will not save history (since no post_save signal is sent). Today, I found the django-field-history plugin which is very similar. I was wondering if anyone that has used this app can tell if it has the same limitation with bulk_update like django-simple-history. I browsed the user guide but could not not see anything relevant. In my models, I only need to track history for a fields so I am considering switching to this option if it works with bulk_update. -
Django channels can't connect
I have problem using channels. They work well with localhost connection but don't work with my wifi ip address connection. But HTTP request works well with my wifi ip connection. Redis Server is opend at ip 0.0.0.0 Drf server is opend at 0:8080 With python redis module, both of localhost and my wifi ip connection are available. Settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('my_wifi_ip_address', 1280)], }, }, } With this code, localhost connection is available but connection with my_wifi_ip_address is not available I'm saying ws://127.0.0.01:8080/ws/chat/ this works ws://my_wifi_ip_address/ws/chat/ this does not work Thanks for your help -
Django admin forgin key show all choices inted of relation
I have three models first model is country second model is cities every country have many cities in third model have two drop menu country and cities in admin panel it show all country and all cities but i want to show all cities to choosen country only -
How to resolve an error 404 for django-social?
I want to be able to login through social media. Followed all the steps (registered app), the login works just fine but does not go through because django does not recognize my url. This is my call to the api endpoint facebookLogin(token: string):any{ return this.http.post(environment.api + 'fblogin/', {token:this.token}).subscribe( (onSucess:any) => { localStorage.setItem(this._tokenKey, onSucess.token) }, onFail => { console.log(onFail) } ); } But I get the following error : POST http://127.0.0.1:8000/api/fblogin/ 404 (Not Found). From this I know there to be something wrong with my django urls. And indeed going to http://127.0.0.1:8000/api/fblogin/ gave me a page not found error and that it tried to match several other urls. However I can't see what is wrong with my urls URLS in my app from django.conf.urls import url, include from rest_framework import routers from . import views from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token from social_django import urls router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'fblogin/', include(urls)), url(r'auth/', obtain_jwt_token), url(r'refresh/', refresh_jwt_token) ] URLS in my project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('Backend.api.urls')) ] Other URLS like http://127.0.0.1:8000/api/users/ do work. I also am under the impression that all of my settings are in … -
DJANGO: Pass a specific variable from template to view when button is pressed
I am building an online store that displays products with various fields to show in the template (name, price, item ID, etc), and I am doing this for every product passed in. So when the page loads I have many tags that share the same name. My problem is that I don't know how to pass the item ID into the next view. This value is the unique identifier so I need it to perform a select statement from my database to retrieve all of the items information. That information can then be displayed on another page where the user can see all details and add it to their cart. I tried to use a hidden form and use POST to get the value but I can't seem to get the exact element that I want since there are many with the same div tag ID. When each item is hovered over, a button appears to view the item details. When that button is pressed, this is where I need to send the item ID from the labeled div tag into the next view. views.py # Products page to view all items def products_page(request): args = { 'products': products, } … -
How to debug django staticfiles served with whitenoise, gunicorn, and heroku?
I've got a project that runs on Heroku from a Dockerfile and heroku.yml. The site generally works, but I am having trouble with static files. collectstatic is run when building the pack. I'm trying to use whitenoise but not sure why it's not working. It sounds so simple so I'm sure it's something silly. heroku.yml setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn records_project.wsgi settings.py MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.sites.middleware.CurrentSiteMiddleware', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', ... more stuff here... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # for referencing files with a URL STATIC_URL = '/static/' # where to find static files when local STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] # location of satatic files for production STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # how Django should look for static file directories; below is default STATICFILES_FINDERS = [ # defaults "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] # This gives me a 500 error # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls.py urlpatterns here... ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
unexpected indent error installing django
Working through book "Django for Beginners". Have successfully completed 3 projects. Starting on Chapter 4. Forgot to exit pipenv from previous project. Created new directory, issued "pipenv install django==2.2.5", which resulted in following: PS C:\users\phil\desktop\django\blog> pipenv install django==2.2.5 Creating a virtualenv for this project… Pipfile: C:\Users\Phil\Desktop\django\Pipfile Using c:\users\phil\appdata\local\programs\python\python38\python.exe (3.8.2) to create virtualenv… [= ] Creating virtual environment...Already using interpreter c:\users\phil\appdata\local\programs\python\python38\python.exe Using base prefix 'c:\users\phil\appdata\local\programs\python\python38' New python executable in C:\Users\Phil.virtualenvs\django-nLBe_sZT\Scripts\python.exe Command C:\Users\Phil.virtu...T\Scripts\python.exe -m pip config list had error code 1 Failed creating virtual environment pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\cli\command.py", line 235, in install pipenv.exceptions.VirtualenvCreationException: retcode = do_install( pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 1734, in do_install pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 570, in ensure_project pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 505, in ensure_virtualenv pipenv.exceptions.VirtualenvCreationException: File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\pipenv\core.py", line 934, in do_create_virtualenv pipenv.exceptions.VirtualenvCreationException: raise exceptions.VirtualenvCreationException( pipenv.exceptions.VirtualenvCreationException: Traceback (most recent call last): File "c:\users\phil\appdata\local\programs\python\python38\lib\runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\phil\appdata\local\programs\python\python38\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 2628, in main() File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 860, in main create_environment( File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1173, in create_environment install_wheel(to_install, py_executable, search_dirs, download=download) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1019, in install_wheel _install_wheel_with_search_dir(download, project_names, py_executable, search_dirs) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1046, in _install_wheel_with_search_dir config = _pip_config(py_executable, python_path) File "c:\users\phil\appdata\local\programs\python\python38\lib\site-packages\virtualenv.py", line 1128, in _pip_config config[key] = … -
How can I fetch all news headlines from nested tags?
For starters, i'm new in Python and i'm working with BS not too long. I am trying to get all the news headlines from all the articles on the website, but for some reason these loops doesn't work properly. But why?! I do not understand.. With this program code I tell the computer that I want to find and fetch all the 'a' tags that are inside multiple nested tags, isn't it? And i'm iterating over a nested tag to the next nested tag so i can fetch the "a" tag which contain the news headline. My code: url = "https://loudwire.com/category/news/" content = sessions.get(url, verify=False).content soup = BeautifulSoup(content, "html.parser") section = soup.findAll('section', {'class': 'blogroll row-standard carbonwidget-taxonomy outgrow no-band'}) for stn in section: blog = stn.findAll('div', {'class': 'blogroll-inner clearfix'}) for blogroll in blog: article = blogroll.findAll('article') for i in article: posts = i.findAll('div', {'class':'content'}) for wrapper in posts: a = wrapper.findAll('a', {'class': 'title'}) for link in a: print(link.get('title')) context = {'contex': link.get_text(strip=True)} return render(request, 'music/news.html', context) So, what am I doing wrong? Maybe you can show me where did i make a mistake and how to do this correctly? Thank you, any help will be invaluable! -
Django using custom icon in admin change list view
I want to have custom links in the change list view in Django admin. Currently, I can setup the links and get the three links in the last column: However, I would like to have three images instead of the text, but I do not know how to reference the static files for the images inside the corresponding models.py file. I tried: def get_icons(self): """ Icons with link for admin """ iconV = reverse('submission_view_details', args=[self.id]) imgV = mark_safe(f"<img src='statics/icons/icon_view.png'>") icon_V = mark_safe(f"<a href={iconV} target=_blank>{imgV} </a>") iconE = reverse('submission_edit', args=[self.id]) icon_E = mark_safe(f"<a href={iconE} target=_blank>Edit </a>") iconP = reverse('submission_pdf', args=[self.id]) icon_P = mark_safe(f"<a href={iconP} target=_blank>Print</a>") return icon_V + icon_E + icon_P #--- but this results in: In principle, the static files are well configured since I use custom css and jquery files stored in the static folder where the icons are located. -
Wndows IIS 10 will not serve static files from Django 2.2. . . How can I fix this?
The website displays to localhost without css, js, or images. I setup Windows IIS according to this blog including the final section about static files. The methods outlined are similar to answers from this question, this question, this blog, and this youtube video on how to serve static files from django with IIS. Django settings: STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') # tested in shell, it is where I expect at the same level as manage.py The directory "static" was created with manage.py collectstatic in the expected STATIC_ROOT location with all of the static files contained The static directory was then added as a virtual directory: Then I removed the django handler I created from the static directories handler mappings: I unlocked the handlers at the root: The django application did display properly, with static files, when I tried using Wampserver w/ Apache and mod_wsgi. Unfortunately, it appears windows IIS will be the better solution for other unrelated reasons. Not too mention Wampserver is a development server, not a production server. I defined a path for the environment variable WSGI_LOG, the logs generated have no errors. Just states wfastcgi.py was initialized and will restart when there are changes to … -
Django InlineFormSet differentiate existing db forms vs extra forms
Consider my database has 2 existing instances of MyModel. My InlineFormSet displays both existing instances and 1 extra. Forms with existing instances only the state can be changed Forms with the extra all fields can be changed How do I achieve this? ==== (user can edit bold; italics is locked) [MyModel1 Name] . . [MyModel1 State] [MyModel2 Name] . . [MyModel2 State] [NewExtra Name] . . [NewExtra State] <-- both can be changed ==== I was trying to use {{ form.name.instance }} vs {{ form.name }} But I don't know how to differentiate between existing instances and extras. # forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ["name", "state"] MyModelFormSet = inlineformset_factory( MyParent, MyModel, form=MyModelForm, can_delete=False, extra=1 ) # views.py class UpdateMyModelsView(UpdateView): template_name = "update_mymodel.html" model = MyParent fields=[] success_url = reverse_lazy('update_success') def get_object(self, *args, **kwargs): return MyParent.objects.get(admin=self.request.user) def get_context_data(self, **kwargs): context = super(UpdateMyModelsView, self).get_context_data(**kwargs) parent= MyParent.objects.get(admin=self.request.user) context['parent'] = parent if self.request.POST: context['mymodel_formset'] = MyModelFormSet(self.request.POST, instance=self.object) else: context['mymodel_formset'] = MyModelFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() mymodel_formset= context['mymodel_formset'] with transaction.atomic(): self.object = context['parent'] if mymodel_formset.is_valid(): mymodel_formset.instance = self.object mymodel_formset.save() else: return super(UpdateMyModelsView, self).form_invalid(form) return super(UpdateMyModelsView, self).form_valid(form) # update_mymodel.html <form method="POST" class="pretty-form"> {% csrf_token %} {{ mymodel_formset.management_form …