Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError - NOT NULL constraint failed in the `models.DecimalField`
I'm trying to build a models.DecimalField which will set to 50 and will have a range (from 50 to 9000) with a step 50. I have read that I can use choices: "A sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field. If choices are given, they’re enforced by model validation and the default form widget will be a select box with these choices instead of the standard text field.". I have no idea how to fix it. For sure error is in quantity = models.DecimalField. My code: from django.db import models # Create your models here. class ProductInquirie(models.Model): email = models.CharField(null=False, blank=False, max_length=120) # max_lenght required tittle = models.TextField(null=False, blank=False) quantity = models.DecimalField( null=True, blank=True, decimal_places=0, max_digits=4, default=50, choices=[(i, i) for i in range(50, 9000, 50)] ) target_price = models.DecimalField(null=False, blank=True, decimal_places=2, max_digits=7) # Why decimal not float: https://docs.python.org/3/library/decimal.html#module-decimal one_time = models.TextField(default="client didn't provide information, or want constant supply") constant_need = models.TextField(default="no information") how_soon = models.TextField(default="no information") Error: Expected behaviour: It should look like this: Unfold, like this: ...but, without errors when saved(till now the error appears when the "save" button is pressed):) -
How to update a foreign key's attribute after creation of object in Django Model
I'm creating a REST API using Django that has two models that relate to each other: Item and Attribute. An Item has Attribute as a foreign key. The Attribute model has a field called number_of_uses which stores the number of items that attribute has associated it with. I wanted to know how I can update that number on the creation of a new Item. How can I update the field after the creation of the item, but before the API returns a response to the caller? -
Django : Celery configuration with Rabbit MQ inside docker
First of all, i've already got a rabbitmq container that launches with my django vm. That's the docker-compose.yml file : version: "3.8" services: web: build: ./src ports: - "${PORT}:${PORT}" depends_on: - message tty: true stdin_open: true container_name: ${COMPOSE_PROJECT_NAME}_app expose: - ${PORT} links: - message env_file: - .env restart: unless-stopped volumes: - ./src:/code message: container_name: ${COMPOSE_PROJECT_NAME}_broker image: rabbitmq:3.9.12-management ports: - "5672:5672" - "15672:15672" restart: always volumes: - ./data:/var/lib/rabbitmq/ env_file: - .env environment: - RABBITMQ_DEFAULT_USER=${RABBITMQ_DEFAULT_USER} - RABBITMQ_DEFAULT_PASS=${RABBITMQ_DEFAULT_PASS} So after installing celery with pypi and following the First Steps, i've created a file **celery.py ** wich are in the same folder that urls.py and settings.py and reading the docs i've used the same rule to _init.py. celery.py : from __future__ import absolute_import import os from celery import Celery from django.conf import settings # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.base') app = Celery('project') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') init.py : from __future__ … -
My cookies are not setting, when i make request in insomnia my cookies are set
When i send request in Insomnia cookies are set, but on client (Vue) i make request to my backend (django) cookies are not set Expected Behaviour: Cookie is set Actual Behaviour: Response status is 200, but the cookies is not set and shows only in developer tools int the network tab Vue request: methods: { loginUser: function () { fetch(`http://127.0.0.1:8000/auth/login/`, { method: "POST", headers: { "content-type": "application/json", }, credentials: 'include', body: JSON.stringify({ username: this.username, password: this.password, }), }) .then((res) => { return res.json(); }) .then((data) => { window.location.replace(data.url); }) .catch((err) => console.error(err)); }, Django EP: @csrf_exempt def loginUser(request): if not request.method == "POST": return HttpResponse(status=405) data = json.loads(request.body.decode('utf-8')) user = authenticate(request, username=data['username'], password=data['password']) request.session.set_test_cookie() if user is not None: login(request, user) return HttpResponse(json.dumps({'url': 'http://localhost:8081/#/notes'})) else: print('Invalid login') return HttpResponse(status=404) test cookie not working (request.session.set_test_cookie()) def getloggeduser(request): print(request.session.test_cookie_worked()) return JsonResponse({'name': ''}) my setting: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'notesapp.apps.NotesappConfig', 'authentication.apps.AuthenticationConfig', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True -
TemplateDoesNotExist at / index.html (Django)
I'm currently trying to get my full stack app (React and Django 4.0) to deploy on Heroku, but when I load the landing page, I get a TemplateDoesNotExist at / index.html error on the page. Like so: However, I can get the django admin page to load just fine. From what I've seen so far, I think my current problem is in my TEMPLATES settings in my settings.py file, but nothing I have changed has worked for me yet. Here is some of the settings.py file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I was following a tutorial since I'm new to Django and I changed my file structure from two directories (one for front-end and one for back-end) to just one like below: My index.html is still located in the public directory and I'm not quite sure if I need to make a templates folder and relay that path in my settings or not. Here's my urls.py: from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from django.conf import … -
Search Engine Optimisation for a Django website
I made a website with Django but I'm stuck with something. How can handle the SEO? Is there any Django module that can help me achieve that. If there isn't, how can I achieve on my own -
Настройка docker-compose.yaml для vue, redis и django [closed]
Я планирую запускать приложение одной командой из терминала. Однако при конфигурировании docker-compose.yaml столкнулся со множеством проблем и пробелов в своих знаниях. Составив наконец этот файл понял что работает только redis а остальное не запускается. Сам Django работает на postgresql, а redis нужен только для нормальной работы celery, которого я пока не хочу добавлять в docker Структура приложения docker-compose.yaml src/web/static/museum/(фронт приложения на vue.js) src/manage.py python/Dockerfile vue-js/Dockerfile python/Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN pip install poetry==1.1.8 && poetry config virtualenvs.create false WORKDIR /app COPY pyproject.toml . RUN poetry install COPY . . RUN python src/manage.py collectstatic --no-input EXPOSE 8000 CMD python src/manage.py migrate && python src/manage.py runserver 0.0.0.0:8000 vue-js/Dockerfile FROM node:lts-alpine WORKDIR /app/src/web/static/museum RUN npm run serve CMD ["npm", "run", "serve"] docker-compose.yaml version: '3' services: redis: image: redis:6-alpine ports: - 6379:6379 vue: image: node:lts-alpine build: context: ./vue-js dockerfile: Dockerfile ports: - 8080:8080 restart: always app: image: django3.2:latest build: context: ./python dockerfile: Dockerfile depends_on: - redis environment: DB_USER: user DB_NAME: name DB_PASSWORD: password CELERY_BROKER_URL: redis://redis:6379/0 restart: always при запуске docker-compose.yaml выдает ошибку app_1 | connection = Database.connect(**conn_params) app_1 | File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect app_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) app_1 | django.db.utils.OperationalError: could not connect to server: Connection refused … -
Django get queryset through Many To Many extra field
i have a Many-to-Many Relationship between two classes object, i need get queryset filtered by a Many-To-Many extra field that are my 3 classes class Card(models.Model): title = models.CharField(max_length=250 ) tags = models.ManyToManyField(Tag, through='Cards_Tags') class Tag(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) class Cards_Tags(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) card = models.ForeignKey(Card, on_delete=models.CASCADE) field = models.CharField( max_length=25, blank=True ) if i use that it works, but it returns a queryset of Cards_Tags i need same result as Tags objects developers = Cards_Tags.objects.filter(card=obj, field='developer') how i can get Tags queryset where m2m relationship in Cards_Tags have field='developer' ? -
Django Edit Profile View not saving new email value
I am (attempting to) implement the ability for a user to edit and update their email address on their profile page. I am getting no errors when doing this end to end but the new email is not being saved to the DB. Everything seems to be working, even the redirect to the profile page in the edit_profile function, but the save() doesn't seem to be working, the users email doesn't update and when I am redirected back to the profile page, the email is still the current value. Thanks! Model: class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) is_pro = models.BooleanField(default=False) is_golfer = models.BooleanField(default=False) def __str__(self): return self.email Form class EditProfileForm(forms.Form): email = forms.EmailField( label='', widget=forms.TextInput(attrs={'class': 'form-field'})) View @login_required def edit_profile(request): if request.method == "POST": form = EditProfileForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] user = CustomUser.objects.get(id=request.user.id) user.save() return redirect("typeA", username=user.username) else: form = EditProfileForm() return render(request, "registration/edit_profile.html", {'form': form}) URLS urlpatterns = [ path('type_a_signup/', ASignUpView.as_view(), name='a_signup'), path('type_b_signup/', BSignUpView.as_view(), name='b_signup'), path('login/', LoginView.as_view(), name='login'), path('password_reset', PasswordResetView.as_view(), name='password_reset'), path('typea/<username>/', typeA, name='typeA'), path('typeb/<username>/', typeB, name='typeB'), path('login_success/', login_success, name='login_success'), path('edit_profile/', edit_profile, name='edit_profile'), ] Template <div class="container"> <div class="form-container"> <h2>Edit profile</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div> {{ form.email.label_tag }} <input type="text" class="form-control {% if … -
Using mptt with Jstree in Django
Only the first element is retrieved in the Jstree without it's children and the other root parent are out of the Jstree The template: <div class='component'> {% recursetree components %} <div id='jstree'> <ul> <li id="child_node_1"> <a>{{ node.name }}</a> {% if not node.is_leaf_node %} <ul class="children"> <li> <a>{{ children }} </a></li> </ul> {% endif %} </li> </ul> </div> the model: class Component(MPTTModel): name = models.CharField(max_length=100) manufacturer = models.CharField(max_length=100) model = models.CharField(max_length=100) serial_number = models.CharField(max_length=255) price = models.IntegerField() note = models.TextField() parent = TreeForeignKey("self", verbose_name=( "Parent Component"), blank=True, null=True, related_name='children', on_delete=models.CASCADE) def __str__(self): return f"{self.id}, {self.name}" -
How to use data from template to send an email in django
I'm trying to make "Ask a question" page where you fill out your full name, email and the message. I need that message to be sent as an email to another email. I haven't done anything in my views since i dont know what to add there for this to work. HTML: <form action="" method="post"> {% csrf_token %} <input type="text" class="form-control" name="name" placeholder="Full name" id="full_name"> <input type="email" class="form-control" name="email" placeholder="Email" id="login-email"> <input type="text" class="form-control" name="text" placeholder="Poruka" id="text"> <input type="submit" class="login-button" value="Login"> </form> -
TemplateDoesNotExist at / index.html (Django)
I've been searching around for answers for awhile now and I haven't come across anything that has worked for me so far. I'm currently trying to get my full stack app (React and Django) to deploy on Heroku. However, I can get the django admin page to load just fine. I think my current problem is in my TEMPLATES settings in my settings.py file, but I'll just include all of the file. """ Django settings for total_weather_backend project. Generated by 'django-admin startproject' using Django 4.0. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os ROOT_PATH = os.path.dirname(__file__) from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-6j01k=wp28&v8%%-7g)oj+c0=)5cd^ssu38m=r0yz7hi2$jji@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['https://total-weather.herokuapp.com/'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', 'djoser', ] MIDDLEWARE = [ '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', … -
apply a filter to the choices field of my model
Hi I have problems with some filters in django. I have my own view where I can choose the day of the week which is a select choice field once chosen it is saved in the db. I would like to filter those already present so as not to repeat them if I had to choose another day. Can anyone help me out please? models.py class Piano(models.Model): nome_piano = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente_piano = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente_piano' ) def __str__(self): return self.nome_piano class Meta: verbose_name = "Piano alimentare" verbose_name_plural = "Piani alimentari" class PianoSingleDay(models.Model): giorni_settimana_scelta = [ ("1","Lunedì"), ("2","Martedì"), ("3","Mercoledì"), ("4","Giovedì"), ("5","Venerdì"), ("6","Sabato"), ("7","Domenica") ] giorni_settimana = models.CharField( choices = giorni_settimana_scelta, max_length = 300 ) single_piano = models.ForeignKey( Piano, on_delete = models.CASCADE, related_name = 'single_piano' ) def __str__(self): return self.giorni_settimana class Meta: verbose_name = "Piano singolo" verbose_name_plural = "Piani singoli" views.py @login_required def PianoSingleView(request, id): piano = get_object_or_404(models.Piano, id = id, utente_piano = request.user) if request.method == 'POST': giorno_form = PianoSingleDayForm(request.POST, prefix = 'giorno') if giorno_form.is_valid(): day_piano = giorno_form.save(commit = False) day_piano.single_piano = piano day_piano.save() return redirect('gestione-piano', id = piano.id) else: giorno_form = PianoSingleDayForm(prefix = 'giorno') context = {'piano': piano, 'giorno_form': … -
Djanog limit image upload size
I am attempting to limit the size of an image that can be uploaded. To do this in the docs I found DATA_UPLOAD_MAX_MEMORY_SIZE I set the value of it to 3mb (3145728 bytes) in my settings.py file but I am still able to upload files larger than 3 mb. I also tried FILE_UPLOAD_MAX_MEMORY_SIZE and the same thing occurred. The only way i can get it to trigger is if i set it to a very low value such as 1 or 2. Any ideas on what I'm doing wrong. -
Unable install package from requirements.txt using pip in vagrant development server using virtaul environment
Unable install the packages from requirements.txt in vagrant development server. Error Message: (env) vagrant@ubuntu-bionic:/vagrant$ pip install -r requirements.txt Collecting django==2.2 (from -r requirements.txt (line 1)) Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f745c06e748>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f745c06e7f0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f745c06e4e0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f745c06e550>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f745c06e908>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/django/ Could not find a version that satisfies the requirement django==2.2 (from -r requirements.txt (line 1)) (from versions: ) No matching distribution found for django==2.2 (from -r requirements.txt (line 1)) requirements.txt django==2.2 djangorestframework==3.9.2 after getting error … -
Could not resolve URL for hyperlinked relationship using view name "v1:resources:profiles:profile_detail"
Im getting this error and have been trying to fix it for hours. I think the problem has something to do with the namespaces. I tried multiple solutions I found on but none of them works. This line -> profile = serializers.HyperlinkedRelatedField(read_only=True, view_name="v1:resources:profiles:profile_detail") gives me an error Could not resolve URL for hyperlinked relationship using view name "v1:resources:profiles:profile_detail. I tried so many solutions and ended up with this tedious nested namespace. Project structure looks something like this manage.py src/ wsgi.py asgi.py urls.py apps/ urls.py authentication/ urls.py resources/ urls.py profiles/ urls.py posts/ websocketchat/ filteringrecommender/ src/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('v1/', include('src.apps.urls', namespace='v1'))] src/apps/urls.py app_name = 'v1' urlpatterns = [ path('auth/', include('src.apps.authentication.urls', namespace='auth')), path('resources/', include('src.apps.resources.urls', namespace='resources')),] src/apps/resources/urls.py app_name = 'resources' urlpatterns = [ path('profiles/', include('src.apps.resources.profiles.urls', namespace='profiles')),] src/apps/resources/profiles/urls.py app_name='profiles' urlpatterns = [ path('', views.ProfileListView.as_view(), name='profiles'), path('<str:profile_id>', views.ProfileDetailView.as_view(), name='profile_detail')] src/apps/authentication/serializers.py class UserSerializer(serializers.ModelSerializer): profile = serializers.HyperlinkedRelatedField(read_only=True, view_name="v1:resources:profiles:profile_detail") class Meta: model = User fields = ('id', 'username', 'email', 'profile') -
How to filter my model objects based on Tree QuerySet from MPTT Django?
I was fighting with creating a categories with parent categories. Similar to this: - Category 1 - SubCategory 1.1 - SubCategory 1.2 - Category 2 I managed to do this with django-mptt and MPTTModel and TreeForeignKey: class Category(MPTTModel): title = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') And I am happy with it, I am doing all the magic in templates and in views.py I am getting 'TreeQuerySet' object. And I can see that it is working (I used method get_family()), if I will send Category 1 then in this TreeQuerySet object I have (Category 1, SubCategory 1.1, SubCategory 1.2) so success. But then I have no idea how to do query based on that. I have object model: class Post(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True, default=None) And I want to make a query through my Post objects with this TreeQuerySet to get Post objects that have category - Category 1 OR SubCategory 1.1 OR SubCategory 1.2 attached. And I was trying many things with union, for loops and other stuff, but it all failed most of the time because object TreeQuerySet doesn't have such and such method. I started to think that I should … -
How to fix CSRF foreign key in [django]
I have an error in DJANGO, I have 2 foreign keys in one of my models, and whenever I want to register a new row, it gives a 403 CSRF error. -
How can i retry a django celery task when I click on retry button of my site?
I am using redis and rabbitmq to put the tasks in queue. I want to add a retry button on my on click of which a particular task can be retried. Please tell me if someone can help me with this. -
The email address of participant is added to all meetings, not just the one he joined. Django
Followed the tutorial on creating meetups and allow participants join them. When adding a participant (his email address) using the form, the email address is added to all meetings, not just the one he joined. I am new to Django, but it seems like the problem is in the ManyToMany relationship. Models.py from django.db import models class Location(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=300) def __str__(self): return f'{self.name} ({self.address})' class Participant(models.Model): email = models.EmailField(unique=True) def __str__(self): return self.email class Meetup(models.Model): title = models.CharField(max_length=200) organizer_email = models.EmailField() date = models.DateField() slug = models.SlugField(unique=True) description = models.TextField() image = models.ImageField(upload_to='images') location = models.ForeignKey(Location, on_delete=models.CASCADE) participants = models.ManyToManyField(Participant, blank=True) def __str__(self): return f'{self.title} - {self.slug}' Views.py from django.shortcuts import render, redirect from .models import Meetup, Participant from .forms import RegistrationForm # Create your views here. def index(request): meetups = Meetup.objects.all() return render(request, 'meetups/index.html', { 'meetups': meetups }) def meetup_details(request, meetup_slug): try: selected_meetup = Meetup.objects.get(slug=meetup_slug) if request.method == 'GET': registration_form = RegistrationForm() else: registration_form = RegistrationForm(request.POST) if registration_form.is_valid(): user_email = registration_form.cleaned_data['email'] participant, _ = Participant.objects.get_or_create(email=user_email) selected_meetup.participants.add(participant) return redirect('confirm-registration', meetup_slug=meetup_slug) return render(request, 'meetups/meetup-details.html', { 'meetup_found': True, 'meetup': selected_meetup, 'form': registration_form }) except Exception as exc: return render(request, 'meetups/meetup-details.html', { 'meetup_found': False }) def confirm_registration(request, meetup_slug): … -
How to get the el-date-picker date value and pass it to django view.py
How to get the el-date-picker date value and pass it to django view.py. pickup_date = request.POST.get('pickup_date') is not working how to make el-date-picker a required field that force user to select a date when filling the form html: <!DOCTYPE html> <html lang="en"> <head> <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">--> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> </head> <style> </style> <body> <form> <div id='app'> <el-date-picker v-model="value" type="date" placeholder="select date" value-format="yyyy-MM-dd" :picker-options="pickerOptions"> </el-date-picker> </div> <button type="submit">submit</button> </form> </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.6/dist/vue.min.js"></script> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <script> var Vue = new Vue({ el: '#app', data: { value:'', pickerOptions: { disabledDate(time) { return time.getTime() <= Date.now() } }, }, created() { }, mounted() { }, methods: { } }) </script> </html> -
can't import markdown in Django project file
I'm having issues importing markdown in the blog_tags.py file I created or anywhere else. I installed it with the line "pip install markdown" and it installed successfully. I checked with "pip freeze" and it is there. However, when I try to import markdown in a .py file it says it can't find the module. code sample code: from django import template from ..models import Post from django.db.models import Count from django.utils.safestring import mark_safe import markdown register = template.Library() @register.simple_tag def total_posts(): return Post.published.count() @register.inclusion_tag('blog/post/latest_posts.html') def show_latest_posts(count=5): latest_posts = Post.published.order_by('-publish')[:count] return {'latest_posts': latest_posts} @register.simple_tag def get_most_commented_posts(count=5): return Post.published.annotate( total_comments=Count('comments') ).order_by('-total_comments')[:count] @register.filter(name='markdown') def markdown_format(text): return mark_safe(markdown.markdown(text)) Have a nice day everyone -
Real-time scraping website with Django: stoppable scraping process and loading bar
What I would like to achieve I would like to make a website that allows users to scrape information from other websites. My goal is to achieve something as follows: User presses "scrape" When the scraping process begins, Django renders a view with a loading message and a "stop" button If the user presses the "stop" button, or if the scraping process terminates, a view with the scraping results is shown Current state At the moment, I have a very simple scraping website with a horrible user experience. After the user presses scrape, I render a view similar to the following one: def scraping_view(request, scraper_args): scrape_results = scrape(scraper_args) # Very long function! return render(request, 'scrape_view.html', scrape_results ) This is a bad idea, as the scrape function takes a long time, and the user experience is terrible. My (probably bad) idea My idea was to: launch a celery task and render an intermediary view with the loading message and a "stop" button let the celery task store the scrape results somewhere (where?) find a way to revoke the task if the user presses the "stop" button retrieve the results of the celery task when the task is finished or when "stop" … -
why my pc not able to install pip packages and also shows no command found when run pip commands?
I tried everything thing but no command found comes everytime, uninstall ..reinstall I have the 3.10.1 version in system also, my script folder shows empty please help me as my Django work hinders due to this -
Django Channels does not work inside a DjangoQ jobs or hooks handler
I am trying to trigger a websocket message when a DjangoQ job ends, but it doesn't work. The same code works inside a views.py APIView that queues the job, but does not work inside my jobs.py handler. It does not generate error. It does nothing. views.py # works (calls consumer handler, websocket event emitted and logged on browser console) from channels.layers import get_channel_layer from asgiref.sync import async_to_sync def event_trigger(): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'event_sync', { 'type': 'send_message_to_frontend', 'message': "event_trigered_from_views" } ) Same code called from hooks.py does not work. Does nothing. hooks.py from channels.layers import get_channel_layer from asgiref.sync import async_to_sync def event_trigger(): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'event_sync', { 'type': 'send_message_to_frontend', 'message': "event_trigered_from_hooks" } ) def import_wallet_completed(task): ic(task.result) event_trigger() Invite.objects.update_or_create( emoji_key=task.result['emoji_key'], defaults={ 'job_status': 'wallet_imported' } ) What could be going on?