Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django homepage without cookie before login
I see "we are using cookies" everywhere. I want to have my homepage without a cookie, if no one is logged in. I am using some REST-queries, if someone is logged in, so later on cookies are needed. Is that possible with django ? How ? I am using django 2.2.6. -
Django- "python manage.py runserver" not working
Hi im new to django and i cant get my web server running. First of all i viewed several of other threads and ive been searching for a solution for 4 hours and i couldn't find any help. So this is what ive done: Installed django using the following "pip install django" Created a project using "django-admin startproject DjangoProject" Went into the directory using "cd DjangoProject" Inputted "python manage.py runserver" into the console and the console doesn't display anything. So ive tried several of methods to solve this issue and have even set up environmental variables C:\Python37\scripts C:\Python37 After setting up environmental variables when i input "python -m django --version" or "python manage.py runserver" i receive an output of "'python' is not recognised as an internal or external command,operable program or batch file." I think i haven't set up my environmental variables properly Have i set up my environmental variables properly? Or have i done something else wrong, I can't seem to figure out the problem. Any Help would be appreciated. -
How I can update my objects in template dynamically?
I have comments on a product on the page. and there is a button to add a comment, which puts a new comment into the database. How can I automatically display a new comment on a page? mytemplate.html <div id="comments"> {% include 'comments.html' %} </div> comments.html {% for comment in comments %} <!-- some code for display comments --> {% endfor %} script.js $("#addComment").on("click", function(e){ e.preventDefault() if ($("#addCommentArea").val() != ""){ data = { commentText: $("#addCommentArea").val(), product_id: "{{ product.id }}" } $.ajax({ type: "GET", url: "{% url 'newcomment' %}", datatype: 'json', data: data, success: function(data){ $("#addCommentArea").val("") } }) } }) -
Type object 'Token' has no attribute 'DoesNotExist'
In urls.py, I added token-auth url and I can successfully get token with right credentials: from rest_framework_jwt.views import obtain_jwt_token .... path('token-auth/', obtain_jwt_token), In Postman I tried to hook this method with jwtToken variable like this: var data = JSON.parse(responseBody); postman.setEnvironmentVariable('jwtToken', data.token); Than I tried to call another URL which starts like this: class MyRequestView(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication, ) def list(self, request): .... In postman, when I call this method I tried to add an Authorization header: Authorization: Bearer {{jwtToken}} // Response: "Authentication credentials were not provided." Authorization: JWT {{jwtToken}} // Response: "Authentication credentials were not provided." Token returns a different response: Authorization: Token {{jwtToken}} > WrappedAttributeError at /mypath type object 'Token' has no attribute 'DoesNotExist' I also tried to add a Bearer Token manually but I still get "Authentication credentials were...." I added rest_framework_jwt among INSTALLED_APPS and my DEFAULT_AUTHENTICATION_CLASSES config has TokenAuthentication, SessionAuthentication and BasicAuthentication. What am I missing? -
Changes to the database are displayed only after restarting gunicorn
The data obtained in the NextPredictionListView in the prediction_next_list.html template is updated immediately. And in LastPredictionsListView (prediction_last_list.html) only after restarting gunicorn. class NextPredictionsListView(ListView): model = Prediction queryset = Prediction.objects.filter(prediction_result=None) template_name = 'app/prediction_next_list.html' class LastPredictionsListView(ListView): queryset = Prediction.objects.filter(~Q(prediction_result=None), date__lt=datetime.now()) template_name = 'app/prediction_last_list.html' -
How to generate unique results is django queryset?
I'm retriving a set of objects in django view using following query: shuffle(query) query2=list(ChannelPost.objects.annotate(num_images=Count('channelpostmedia')).filter(num_images__gt=0).order_by('-user_like').distinct()[:6]) query4=list(CommunityPost.objects.distinct().annotate(num_images=Count('communitypostmedia')).filter(num_images__gt=0).order_by('-user_like')[:16]) query3=list(Communities.objects.distinct().order_by('-points')[:5]) query5=list(channel.objects.distinct().order_by('-chaneldate')[:9]) shuffle(query2) shuffle(query3) shuffle(query4) shuffle(query5) query6=list(post.objects.order_by('-DatePosted')) The main problem with the queryset is the fact that the result always contain duplicate objects which is undesirable. -
AttributeError: 'Settings' object has no attribute 'MEDIA'
I'm trying to do (shopping cart web page) using python and django I'm getting this error when I try to run (python manage.py makemigrations) File "D:\projects\myenvironment\lib\site-packages\django\conf__init__.py", line 57, in getattr val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'MEDIA' this is the link for the project on GitHub https://github.com/aaheggy/shoppingWeb Please Help enter image description here -
How to set python timedelta < 0 condition on html
I'm creating a condition on my HTML template and the condition needs to check if a particular timedelta is negative or not. {% if discrepancy.CurrentDiffs < 0 %} Do something {% else %} Do something else {% endif %} It doesn't throw any error but it runs the code in the else statement. -
Getting an Error when running makemigrate on Product model fields that have been added to an existing model
Admittedly I’m a newbie to django and I’m getting the following error when trying to run python manage.py makemigrations I’m trying to add a new field in to my class Product(models.Model): featured = models.BooleanField() Code from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) # max_length = required description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10000) summary = models.TextField() featured = models.BooleenField() #only new added line Error: AttributeError: module 'django.db.models' has no attribute 'BooleenField' command: python manage.py makemigrations <enter> entire_traceback: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\.....\trydjango\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\.....\trydjango\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\.....\trydjango\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\.....\trydjango\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\.....\trydjango\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\.....\trydjango\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\.....\src\products\models.py", line 4, in <module> class Product(models.Model): File "C:\.....\src\products\models.py", line 9, in Product … -
Two Django Views that throw "Internal Error 500" only when in production
I have a website that works perfectly fine in my development environment but throws an Internal Error (500) in production on a Debian 9, Nginx, and Gunicorn setup. Here are the troublesome views: @login_required def post(request): if request.method == "POST": form = ListingForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.lat, post.lng = get_lat_lng(google_api_key, post.street_address + ", " + post.city + ", " + post.state) post.save() return redirect('post_view', pk=post.pk) else: form = ListingForm() return render(request, 'post.html', {'form': form}) @login_required def post_edit(request, pk): post = get_object_or_404(Listing, pk=pk) if request.method == "POST": form = ListingForm(request.POST, request.FILES, instance=post) if form.is_valid(): post = form.save(commit=False) post.lat, post.lng = get_lat_lng(google_api_key, post.street_address + ", " + post.city + ", " + post.state) post.save() return redirect('post_view', pk=post.pk) else: form = ListingForm(instance=post) return render(request, 'post_edit.html', {'form': form, 'post': post}) And here is an example of a view that works completely fine in production with similar functionality: @login_required def new_attorney(request): if request.method == "POST": form = AttorneyForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('attorney_edit', pk=post.pk) else: form = AttorneyForm() return render(request, 'new_attorney.html', {'form': form}) I'm kind of freaking out because this is a time sensitive project we need live soon, and I have no clue what's causing this error. … -
Error installing psycopg2 python 3.7 on macos 10.15
I tried pip3 install psycopg2 Got these errors, unable to understand what I need to do. Collecting psycopg2==2.7.3.1 Using cached https://files.pythonhosted.org/packages/6b/fb/15c687eda2f925f0ff59373063fdb408471b4284714a7761daaa65c01f15/psycopg2-2.7.3.1.tar.gz Installing collected packages: psycopg2 Running setup.py install for psycopg2: started Running setup.py install for psycopg2: finished with status 'error' ERROR: Command errored out with exit status 1: command: /Users/amolchakane/Desktop/Projects/kisanoauth/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/c7/wshj0hq9637_ddn00y_52y7c0000gp/T/pycharm-packaging/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/c7/wshj0hq9637_ddn00y_52y7c0000gp/T/pycharm-packaging/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/c7/wshj0hq9637_ddn00y_52y7c0000gp/T/pip-record-f050z4mz/install-record.txt --single-version-externally-managed --compile --install-headers /Users/amolchakane/Desktop/Projects/kisanoauth/venv/include/site/python3.7/psycopg2 cwd: /private/var/folders/c7/wshj0hq9637_ddn00y_52y7c0000gp/T/pycharm-packaging/psycopg2/ Complete output (61 lines): running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.7 creating build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_json.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extras.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/errorcodes.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/tz.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_range.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_ipaddress.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/init.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/psycopg1.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extensions.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/sql.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/pool.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 creating build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_transaction.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/dbapi20.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_extras_dictcursor.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_with.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_types_basic.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_bug_gc.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_module.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_psycopg2_dbapi20.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_async.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_dates.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_async_keyword.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/testutils.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_connection.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_copy.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/test_bugX000.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests copying tests/init.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2/tests … -
I need to know my social database design is good or need to re-disign
I have a dream to design a social network and I design a database. please wrote opinion to about my schema and if they have problem guide me. thanks. class User(AbstractUser): """ Custom User Model """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bio = models.TextField(max_length=500, blank=True) class UserFriend(models.Model): FRIEND_STATUS = [ ('0' , 'Pending'), ('1' , 'Accepted'), ('2' , 'Declined'), ('3' , 'Blocked'), ] FRIEND_TYPE = [ ('0' , 'Friend'), ('1' , 'Close Friend'), ('2' , 'Classmate'), ('3' , 'Family'), ('4' , 'Follower') ] status = models.CharField(max_length=1, choices=FRIEND_STATUS) type = models.CharField(max_length=1, choices=FRIEND_TYPE) user_id = models.ForeignKey(User, on_delete=models.CASCADE) friend_id = models.ForeignKey(User, on_delete=models.CASCADE) class Profile(models.Model): """ profile model """ GENDER_CHOICES = [ ('M' , 'Male'), ('F' , 'Female'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=2, choices=GENDER_CHOICES) birthday = models.DateField(null=True, blank=True) birthplace = models.CharField(max_length=150, null=True, blank=True) address = models.CharField(max_length=250, null=True, blank=True) education = models.CharField(max_length=150, null=True, blank=True) skill = models.CharField(max_length=150, null=True, blank=True) language = models.CharField(max_length=150, null=True, blank=True) college = models.CharField(max_length=150, null=True, blank=True) favorite_sport = models.CharField(max_length=150, null=True, blank=True) favorite_food = models.CharField(max_length=150, null=True, blank=True) favorite_movie = models.CharField(max_length=150, null=True, blank=True) I create a user entity class and when user create a post or something else first app create a record in this table and then create record for … -
Cannot download Pillow in Django VSCode project (Windows)
I'm going through Django 2.2 course with Windows / VSCode / Anaconda setup. I've tried to use both Python 3.6 and 3.7 interpreters and tried to download Pillow with commands such as: pip install Pillow python -m pip install pillow pip install Pillow==5.0.0 I've tried to execute this both in is Anaconda Shell Prompt and cmd. Simply put, I get error of missing Pillow package whatever I do. When I try to execute "conda install" it says the the requirement is already satisfied, but it still doesn't recognize the package. See attached pictures about errors. Error1 Error2 -
Invalid Column name error when attempting to delete model instance
A little bit of context: I have a Django site, where I just overwrote the default user model mid project. It appears to be working for everything, except for on the admin page if I try to delete a user instance, it gives an error Invalid column name 'ouser_id'. I tried removing the automatically created delete functionality within the admin site, and adding my own as an action, but that did not work. models.py class OUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) username = models.CharField(max_length=150, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # a superuser first_name = models.CharField(max_length=100, blank=True, default='') last_name = models.CharField(max_length=100, blank=True, default='') date_joined = models.DateField(auto_now=True) password = models.CharField(max_length=100) REQUIRED_FIELDS = [] # Email & Password are required by default. USERNAME_FIELD = 'username' def __str__(self): return self.username def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True admin.py class OUserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserAdminChangeForm add_form = UserAdminCreationForm actions = [deleteOUser, setStaff, setNotStaff, setSuperuser, setNotSuperuser, setActive, setInactive, … -
ImportError: Can't import DEFAULT_CHANNEL_LAYER
I am developing a web service based on Django and channels, I can run the app locally using daphne server, but the problem comes when I deploy it on Heroku, I get import error, the error says cannot import DEFAULT_CHANNEL_lAYER... The app is running locally and it was running on Heroku until I decided to include channels. -
Django different url going to the same page
I am trying to create 2 extra pages on my Django site, I created the first one with no problem (calendar.html) but when I try to create the second one (actionplan.html) it gives me no error, but when I access xxx/actionplan.html , it shows the calendar.html page... I cannot access xxx/actionplan.html This is my urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from django.views.generic import TemplateView from django.views.generic.detail import DetailView urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), url(r'xxx', TemplateView.as_view(template_name="calendar.html")), url(r'^xxx/$', DetailView.as_view(template_name="actionplan.html")), url(r'^admin/', admin.site.urls), url(r'^', include('blog.urls'), name="Blog"), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) This is my views.py: from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' class Calendar(generic.DetailView): model = Post template_name = 'calendar.html' class Planoacao(generic.DetailView): model = Post template_name = 'actionplan.html' I have tried: url(r'^xxx/$', DetailView.as_view(template_name="actionplan.html")), url(r'^xxx', DetailView.as_view(template_name="actionplan.html")), url(r'^xxx$', DetailView.as_view(template_name="actionplan.html")), url(r'xxx', DetailView.as_view(template_name="actionplan.html")), I am officially out of ideas now... can anyone spot a problem? -
Chromium print-to-pdf adding space above images
The background I have a simple document making system which is part of a Python Django application. The PDF download uses Chromium's print-to-pdf function running from a Docker container by passing in the URL of the document page from the Django app. The HTML is edited using TinyMCE. The problem Large gaps are appearing above some images with no obvious difference between the ones that do and the ones that don't have gaps. I have put borders around HTML tags with differing colours to try and see what is containing the empty space: div: red p: green span: blue img: black td: orange The evidence The offending section of the page looks like this in the browser: The resulting PDF looks like this with a big gap in the middle: The HTML for that section is: <div class="content flex None"> <div class="docsection flex"> <div class="wrapper"> <div class="header" style="position: relative;"> <!-- the trigger element if no value set yet --> <a href="" id="docsection_title70-btn" class="text-darken-2 inplace-editor-trigger error" style="" data-for="docsection_title70"> Add title </a> <!-- the actual output content if there is any yet --> <h2 class="inplace-editor-content tooltip title" data-position="top" data-tooltip="Click to edit" data-for="docsection_title70"> </h2> </div> <div class="copy tinymce" style="position: relative;"> <!-- the trigger … -
Please explain the line of code I Mentioned
This is a mixin which I had seen in a book. from django.core.cache import caches from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_cookie class CachePageVaryOnCookieMixin: cache_name = 'default' @classmethod def get_timeout(cls): if hasattr(cls, 'timeout'): return cls.timeout cache = caches[cls.cache_name] return cache.default_timeout @classmethod def as_view(cls, *args, **kwargs): view = super().as_view(*args, **kwargs) view = vary_on_cookie(view) view = cache_page(timeout = cls.get_timeout(), cache = cls.cache_name)(view) return view In as_view() view = cache_page(timeout = cls.get_timeout(), cache = cls.cache_name)(view) what is the use of (view) at last. Is it a type casting? -
Django: How do I check if a queryset is empty?
I have the following try catch block on a query that I am making: # We only want SurfGroups per SurfInstructor for a forward looking date: try: surf_groups = SurfGroup.objects.filter( instructor__uuid=uuid, date__gte=datetime.date.today() ) except SurfGroup.DoesNotExist: # Handle exception here However, even if the surf_groups queryset is empty, returning no results, the exception can not be handled as it is not thrown on a objects.filter() call. So, my question is, how would I handle an empty queryset? -
Call an another method right after calling model class constructor (Django)
I want to set my Order Object's total amount with the total of selected products (order_items) prices at that time. I want to call an another method right after Order constructor, So that the amount won't change when change in Product price My Order Class is: class Order(models.Model): user = models.ForeignKey(User, on_delete=models. order_items = models.ManyToManyField(OrderItem, related_name="order_items") amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) ......... My OrderItem Class is: class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ........ My Product Class is: class Product(models.Model): name = models.CharField(max_length=30, default=None) price = models.DecimalField(max_digits=10, decimal_places=2) product_type = models.ForeignKey(ProductType, on_delete=models.SET_DEFAULT,default = None, null=True, blank=True) ...... -
How to use token form of django-otp in django for admin verification
I would like to implement a 2 factor authentication system for the admin page in django using django-otp's token form i.e it will ask for a generated otp to verify the authenticated user . I am unaware of how to do this though. As always, I greatly appreciate your suggestions! Note: I am using django 2.2 with python 3.6 I am going make the otp available to admins via email Also, if you need any other reasonable info, feel free to ask! -
is there way for add paginator to search results when i using 'chain' (multi models ) in django
i want to ask if there any way for add paginator to my search results when i'm using chian i mean like this (Multi Databases) i have tried many ways for do this but it's doesn't work i have this in views.py def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: home_database= Homepage.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcprograms_database= PCprogram.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidapk_database= AndroidApks.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidgames_database= AndroidGames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) antiruvs_database= Antivirus.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) systems_database= OpratingSystems.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcgames_database= PCgames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) results= list(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database)) paginator = Paginator(results, 2) # Show 25 rows per page page = request.GET.get('search-page') results = paginator.get_page(page) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') and this in html : {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h2> Results for <b><i style="color:#337ab7">{{ request.GET.q }}</i></b> : </h2> <br/><br/> {% for result in results %} <label id="label_main_app"> <img style="margin-top:.3%;margin-left:.3%" id="img_main_app_first_screen" src="{{result.app_image.url}}" alt="no image found !" height="160" width="165" > {{result.name}} <br><br> <p id="p_size_first_page"> {{result.app_contect}} … -
How can I show selenium web driver process on my django web site?
I am trying to scrap through a dozen websites and show thier result on my own website. My first idea was to put each result url on a iframe. I am using selenium for python which shows you the process of scraping on a browser (web driver) Is there a way to show this process on website in different iframes or something else? I am using django for the website. -
How can to start tasks with celery-beat?
Why i can't run a periodic tasks? proj/settings.py REDIS_HOST = 'localhost' REDIS_PORT = '6379' CELERY_BROKER_URL = 'redis://localhost:6379' BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT CELERY_BEAT_SCHEDULE = { 'task-first': { 'task': 'app.tasks.one', 'schedule': timedelta(seconds=1) }, 'task-second': { 'task': 'app.tasks.two', 'schedule': crontab(minute=0, hour='*/3,10-19') } } proj/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) proj/__init.py__ from .celery import app as celery_app __all__ = ['celery_app'] celery -A proj worker -l info [2019-10-31 16:57:57,906: INFO/MainProcess] Connected to redis://localhost:6379// [2019-10-31 16:57:57,912: INFO/MainProcess] mingle: searching for neighbors [2019-10-31 16:57:58,927: INFO/MainProcess] mingle: all alone [2019-10-31 16:57:58,951: INFO/MainProcess] celery@lexvel-MS-7A72 ready. Tasks are found celery -A proj beat -l info Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2019-10-31 16:58:02,851: INFO/MainProcess] beat: Starting... The celerybeat.pid and celerybeat-shedule files are created. But besides these lines nothing more is displayed. tasks @task() def one(): print('start 1', datetime.now()) driver = init_driver() parse(driver) driver.close() driver.quit() @task() def two(): print('start 2', datetime.now()) driver = init_driver() parse2(driver) driver.close() driver.quit() print('end 2', datetime.now()) -
Heroku logs says: "No web processes running"
I made a website with django and tried deploying it using Heroku. After deploying, I can't access to it and Heroku log shows the following error : at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=pur-beurre-oc8.herokuapp.com request_id=9e33d4c8-83d6-4214-baf8-e4d1023b43ff fwd="176.134.6.63" dyno= connect= service= status=503 bytes= protocol=https After looking through some similar problems, I tried: heroku ps:scale web=1 and got: Scaling dynos... ! ▸ Couldn't find that process type (web). I tried to remove and add buildpacks: heroku buildpacks:clear heroku buildpacks:add --index heroku/python but this last command return to me: Error: Expected an integer but received: heroku/python at Object.parse (/snap/heroku/3832/node_modules/@oclif/parser/lib/flags.js:17:19) at Parser._flags (/snap/heroku/3832/node_modules/@oclif/parser/lib/parse.js:152:49) at Parser.parse (/snap/heroku/3832/node_modules/@oclif/parser/lib/parse.js:113:28) at Object.parse (/snap/heroku/3832/node_modules/@oclif/parser/lib/index.js:25:27) at Add.parse (/snap/heroku/3832/node_modules/@oclif/command/lib/command.js:83:41) at Add.run (/snap/heroku/3832/node_modules/@heroku-cli/plugin-buildpacks/lib/commands/buildpacks/add.js:7:36) at Add._run (/snap/heroku/3832/node_modules/@oclif/command/lib/command.js:44:31) So I do not know what I'm doing wrong My Proficle is like this: web: gunicorn pur_beurre.wsgi I tried to change Procfile like this: web: gunicorn pur_beurre:app or this: web gunicorn pur_beurre:app but heroku ps:scale web=1 still not working