Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unknown Indentation Error in the following code
this is the code: 3nd line is giving error. class RawMassegeForm(forms.Form): subject = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Enter your Subject'})) name = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Enter your Name'})) email = forms.EmailField(widget= forms.EmailInput(attrs={'placeholder':'Enter your email'})) message = forms.TextField(widget= forms.Textarea(attrs={'placeholder':'Enter Your Message here...'})) -
i want to create a MY ACCOUNT or MY PROFILE page on my django website. but my "account.html" template doesnt render
below is the VIEWS.PY code from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Tutorial from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import NewUserForm from .models import Tutorial, TutorialCategory, TutorialSeries from django.http import HttpResponse from django.contrib.auth.decorators import login_required def single_slug(request, single_slug): # first check to see if the url is in categories. categories = [c.category_slug for c in TutorialCategory.objects.all()] if single_slug in categories: matching_series = TutorialSeries.objects.filter(tutorial_category__category_slug=single_slug) series_urls = {} for m in matching_series.all(): part_one = Tutorial.objects.filter(tutorial_series__tutorial_series=m.tutorial_series).earliest("tutorial_published") series_urls[m] = part_one.tutorial_slug return render(request=request, template_name='main/category.html', context={"tutorial_series": matching_series, "part_ones": series_urls}) tutorials = [t.tutorial_slug for t in Tutorial.objects.all()] if single_slug in tutorials: this_tutorial = Tutorial.objects.get(tutorial_slug=single_slug) tutorials_from_series = Tutorial.objects.filter(tutorial_series__tutorial_series=this_tutorial.tutorial_series).order_by('tutorial_published') this_tutorial_idx = list(tutorials_from_series).index(this_tutorial) return render(request=request, template_name='main/tutorial.html', context={"tutorial": this_tutorial, "sidebar": tutorials_from_series, "this_tut_idx": this_tutorial_idx}) return HttpResponse(f"'{single_slug}' does not correspond to anything we know of!") #homepage def homepage(request): return render(request=request, template_name='main/categories.html', context={"categories": TutorialCategory.objects.all}) #register function def register(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, f"New Account Created: {username}") login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, f"{msg}: {form.error_messages[msg]}") form = NewUserForm return render(request, "main/register.html", context={"form":form}) #logout def logout_request(request): logout(request) … -
Retrieve data from queryset and pass to template in django
I have a model as bellow: class Artwork(models.Model): title = models.CharField(max_length=120) collection = models.CharField(max_length=120,null=True) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=0) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) banner = models.ImageField(upload_to='artworks/banner') video = models.FileField(upload_to='artworks/video',blank=True,null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=15) views_count = models.IntegerField(default=150) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) created = models.DateTimeField(default=timezone.now) and The view as bellow: def artwork_list_view(request): queryset = Artwork.objects.all() context = { 'objet_list':queryset, } return render(request, "artworks/list.html", context) I use the queryset in template as bellow: <div style='min-height:80px;'><p >First Collection</p></div> {% for obj in object_list %} <div class="workSeriesThumbnailStrip"> {% if obj.image %} <a href="{{ obj.get_absolute_url }}"><img src="{{ obj.image.url }}" style="float:left;width:67px;height:87px;margin:10px;" ></a> {% endif %} </div> {% endfor %} </div> know I have more than one collection and want to place a for loop in collections to show items of each collection in one row. But as I'm new in django, I don't know how to retrieve the list of collections and pass them to template. please help me. -
Django, Docker and SMTP - messages don't send
I'm trying to send an email through Django and a namshi/smtp Docker image. Code: settings.py: EMAIL_HOST = 'smtp' EMAIL_PORT = '25' DEFAULT_FROM_EMAIL = 'noreply@<domain name here>' # obviously, domain name is set here docker-compose.yml: smtp: image: namshi/smtp restart: always ports: - '25:25' volumes: - ./:/web environment: - KEY_PATH=/web/config/ssl_keys/privkey.pem - CERTIFICATE_PATH=/web/config/ssl_keys/fullchain.pem I'm using django-allauth to send a password reset email. This is the console output when I request for password reset for my account with a valid Yandex email address: smtp_1 | 282 LOG: MAIN smtp_1 | 282 <= noreply@<domain> H=<project name>_web_1.<project name>_default (<some sort of id>) [<some ip here>] P=esmtp S=8248 id=<i feel like it's better if i remove this>@<some sort of id> smtp_1 | 282 LOG: smtp_connection MAIN smtp_1 | 282 SMTP connection from shpplace_web_1.shpplace_default (<some sort of id>) [<some ip>] closed by QUIT web_1 | <my ip?>:34856 - - [25/Apr/2020:21:09:33] "POST /accounts/password/reset/" 302 - smtp_1 | 283 Exim version 4.92 uid=101 gid=101 pid=283 D=80001 smtp_1 | Berkeley DB: Berkeley DB 5.3.28: (September 9, 2013) smtp_1 | Support for: crypteq iconv() IPv6 GnuTLS move_frozen_messages DANE DKIM DNSSEC Event OCSP PRDR SOCKS TCP_Fast_Open smtp_1 | Lookups (built-in): lsearch wildlsearch nwildlsearch iplsearch cdb dbm dbmjz dbmnz dnsdb dsearch nis nis0 passwd … -
How to change title for the tab of User Change Page of Django admin?
I'm working on Django and wanted to change the default title for the tab of User Change Page of Django admin as marked in the pic : my admin.py file is: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_list_template='change_list_form.html' change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So can we change it?? If yes then how?? Thanks in advance!! -
Django : How to show logged in users data from database
I am working on invoice management system having in which user can add invoice data and it will save in database and whenever user logged in the data will appear on home page.but the problem if whenever any user logged in the home page showing other users data also but i want active users data only. could you guys help me. here is my home page,you can see i am logged in through user 1 but at home page user 2 data also appear here is my code views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Invoicelist def home(request): context = { 'invoices': Invoicelist.objects.all() } return render(request, 'invoicedata/home.html', context) class InvoiceListView(ListView): model = Invoicelist template_name = 'invoicedata/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'invoices' class InvoiceDetailView(DetailView): model = Invoicelist class InvoiceCreateView(LoginRequiredMixin, CreateView): model = Invoicelist fields = ['issuer','invoice_number','date','amount','currency','other'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class InvoiceUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Invoicelist fields = ['issuer','invoice_number','date','amount','currency','other'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): invoice = self.get_object() if self.request.user == invoice.author: return True return False class InvoiceDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Invoicelist success_url = '/' … -
coveralls doesn't recognize token when dockerized django app is run in TravisCI, but only from pull requests
I'm getting this error from TravisCI when it tries to run a Pull Request coveralls.exception.CoverallsException: Not on TravisCI. You have to provide either repo_token in .coveralls.yml or set the COVERALLS_REPO_TOKEN env var. The command "docker-compose -f docker-compose.yml -f docker-compose.override.yml run -e COVERALLS_REPO_TOKEN web sh -c "coverage run ./src/manage.py test src && flake8 src && coveralls"" exited with 1. However, I do have both COVERALLS_REPO_TOKEN and repo_token set as environment variables in my TravisCI, and I know they're correct because TravisCI passes my develop branch and successfully sends the results to coveralls.io: OK Destroying test database for alias 'default'... Submitting coverage to coveralls.io... Coverage submitted! Job ##40.1 https://coveralls.io/jobs/61852774 The command "docker-compose -f docker-compose.yml -f docker-compose.override.yml run -e COVERALLS_REPO_TOKEN web sh -c "coverage run ./src/manage.py test src && flake8 src && coveralls"" exited with 0. How do I get TravisCI to recognize my COVERALLS_REPO_TOKEN for the pull requests it runs? -
Writing to txt file in UTF-8 - Python
My django application gets document from user, created some report about it, and write to txt file. The interesting problem is that everything works very well on my Mac OS. But on Windows, it can not read some letters, converts it to symbols like é™, ä±. Here are my codes: views.py: def result(request): last_uploaded = OriginalDocument.objects.latest('id') original = open(str(last_uploaded.document), 'r') original_words = original.read().lower().split() words_count = len(original_words) open_original = open(str(last_uploaded.document), "r") read_original = open_original.read() characters_count = len(read_original) report_fives = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-5.txt", 'w', encoding="utf-8") # Path to the documents with which original doc is comparing path = 'static/other_documents/doc*.txt' files = glob.glob(path) #endregion rows, found_count, fives_count, rounded_percentage_five, percentage_for_chart_five, fives_for_report, founded_docs_for_report = search_by_five(last_uploaded, 5, original_words, report_fives, files) context = { ... } return render(request, 'result.html', context) report txt file: ['universitetindé™', 'té™hsili', 'alä±ram.', 'mé™n'] was found in static/other_documents\doc1.txt. ... -
How to get two distinct objects from the same view function in django according to the requirements?
I have 3 models in Django which are like: class Category(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) class Subcategory(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) class Product(models.Model): name = models.CharField(max_length=200, unique=True) category = models.ForeignKey(Subcategory, on_delete=models.CASCADE, related_name='products') slug = models.SlugField(max_length=150, unique=True) The view function which I want to modify currently looks like this: def product_list(request, category_name): subcategory = get_object_or_404(Subcategory, slug=category_name) subcategory_name = subcategory.name product_list = subcategory.products.all() context = { 'name':subcategory_name, 'product_list':product_list, } return render(request, 'products/product_list.html', context) In one of my html templates each category is displayed along with the subcategories under it. If anyone clicks on the category name instead of the subcategory under that category name, I want the views function to display all the products which come under that category and not just one subcategory under that given category. I can create a separate view to do that but I want to know if there's a way to do that in the same view function. -
django get model help pls by raxim
I have 3 Profil Stimul_Slov and OTVET model inside Stimulus_words there are questions, the participant must answer questions and questions must be saved on the OTVET model how can I put out Stimulus_words questions and save answers to OTVET models.py from django.db import models from django.contrib.auth.models import User class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=100, blank=True) age = models.DateField(blank=True) specialite = models.CharField(max_length=100,blank=True) language = models.CharField(max_length=100,blank=True) def __str__(self): return self.fullname class Stimul_slov(models.Model): stimulus = models.CharField(max_length=200, blank=True) def __str__(self): return "%s" % ( self.stimulus) class Otvet(models.Model): answer = models.CharField(max_length=200, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) stimul = models.ForeignKey(Stimul_slov, on_delete=models.CASCADE) def __str__(self): return "%s: %s ----> %s" % (self.user ,self.stimul, self.answer) -
No ID assigned to objects when created in Django
I have a Class in my models.py named Order class Order(models.Model): customer_name = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer_name', ) order_individual_price = models.IntegerField(default=1) order_name = models.CharField(max_length=200) order_quantity = models.IntegerField(default=1) order_total_price = models.IntegerField(default=1) def __str__(self): return self.order_name In my views.py I create a new instance of order when a button is pressed def ordering(request): latest_order = Order.objects.all() menu = Menu.objects.all() if request.method == 'POST': if request.user.is_authenticated: menu_instance = request.POST.get('add') if menu_instance: get_order = Menu.objects.get(id=menu_instance) get_price = get_order.Menu_price new_order = Order.objects.create(customer_name=request.user, order_name=get_order, order_individual_price=get_price) return redirect('shop-ordering') order_instance = request.POST.get('delete') else: messages.info(request, f'Please Sign In First') return redirect('login') return render(request, 'shop/ordering.html', {'title':'Ordering', 'latest_order': latest_order, 'menu':menu}) However, when I try to get the ID of the object it throws this error Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/alan/Desktop/FRIENDS_CAFE_DJANGO/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/alan/Desktop/FRIENDS_CAFE_DJANGO/venv/lib/python3.8/site-packages/django/db/models/query.py", line 415, in get raise self.model.DoesNotExist( shop.models.Order.DoesNotExist: Order matching query does not exist. I didn't touch any of the init files and since django creates the ID automatically, I'm really confused on why its not assigning each order a ID. -
I want to make multi step form using django form wizard so if anyone has done a project on it please do share
I am doing a project on multi step form in django and i need to make 5 step multi form with different details in it so if anyone has made it do share it with me. Thanks -
Django query based on another query results
I have 4 models in my simplified design class modelA(models.Model): name = models.CharField() class modelsUser(model.Model): username = models.CharField() class bridge(models.Model): user = models.ForeignKey(modelUser, on_delete=models.CASCADE, related_name='bridges') modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='bridges') class subModelA(models.Model): modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='subModelAs') value = models.IntegerField() class subModelB(models.Model): modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='subModelBs') text = models.TextField() What I am trying to to is to get all subModelBs and subModelAs that are for modelAs for which given modelUser have bridge. I've started with this: user = modelUser.objects.get(pk=1) bridges = user.bridges.all() What I've been thinking is something like this: subModelBs = modelB.objects.filter(modelA__in=bridges__modelA) but unfortunately it doesn't work because of error that __modelA is not defined. Is there any proper way to do this? -
How exactly does CASCADE work with ManyToMany Fields in Django
Im Wondering how exactly does CASCADE work with ManyToMany Fields in Django. A short example: class Project(Model): name = TextField(null=False) class Job(Model): projects = ManyToManyField(Project, on_delete=CASCADE, null=False) name = TextField(null=False) As you can see I have a ManyToManyField here. So basically a Project can have mutiple Jobs and a Job can belong to Multiple different Projects. What I want is that a Job is automatically deleted only when all Projects it belongs to are deleted. Does CASCADE work like that in this scenario? -
Can you tell me where is my mistake? I am continuously getting FALSE form.is_valid()
can you look at my code and tell me where is my mistake? I have a form class AddEditTaskForm, which has several fields and it is getting tasks_list in order to get task.list id. forms.py class AddEditTaskForm(ModelForm): def __init__(self,user,*args,**kwargs): super().__init__(*args,**kwargs) task_list=kwargs.get('initial').get('task_list') self.fields['task_list'].value=kwargs['initial']['task_list'].id due_date=forms.DateField(widget=forms.DateInput(attrs={'type':'date'}),required=False) title=forms.CharField(widget=forms.widgets.TextInput()) description=forms.CharField(widget=forms.Textarea(), required=False) completed=forms.BooleanField(required=False) def clean_created_by(self): return self.instance.created_by class Meta: model = Task exclude = [] After rendering a form. I am getting form is not valid error. views.py @login_required def list_detail(request,list_id=None,list_slug=None,view_completed=False): task_list=get_object_or_404(TaskList,id=list_id) tasks=Task.objects.filter(task_list=task_list.id) form=None if view_completed: tasks=task.filter(completed=True) else: tasks=tasks.filter(completed=False) if request.POST.getlist("add_edit_task"): form = AddEditTaskForm(request.user,request.POST,initial={'task_list':task_list}) if form.is_valid(): new_task = form.save(commit=False) new_task.created_by = request.user new_task.description = bleach.clean(form.cleaned_data["description"], strip=True) form.save() messages.success(request, 'New task "{t}" has been added.'.format(t=new_task.title)) return redirect(request.path) else: messages.success(request,'form is not valid') context={ 'list_id': list_id, 'list_slug': list_slug, 'task_list': task_list, 'tasks':tasks, 'form':form, 'view_completed':view_completed, } return render(request,'todo/list_detail.html',context) -
Django: How to fetch data from two models and display it i template?
There are two models Product and ProductImage my code is as follows: models.py class Product(models.Model): product_name = models.CharField(max_length=100) product_weight = models.CharField(max_length=30) models.py from django.db.models.signals import post_save, pre_save from django.dispatch import receiver _UNSAVED_IMAGEFIELD = 'unsaved_imagefield' def upload_path_handler(instance, filename): import os.path fn, ext = os.path.splitext(filename) return "images/{id}/{fname}".format(id=instance.product_id, fname=filename) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) image = models.ImageField(upload_to=upload_path_handler, blank=True) @receiver(pre_save, sender=ProductImage) def skip_saving_file(sender, instance, **kwargs): if not instance.pk and not hasattr(instance, _UNSAVED_IMAGEFIELD): setattr(instance, _UNSAVED_IMAGEFIELD, instance.image) instance.image = None @receiver(post_save, sender=ProductImage) def update_file_url(sender, instance, created, **kwargs): if created and hasattr(instance, _UNSAVED_IMAGEFIELD): instance.image = getattr(instance, _UNSAVED_IMAGEFIELD) instance.save() views.py def products(request): products = Product.objects.all() context = { 'products' : products } return render(request, 'products/products.html', context) products.html {% if products %} {% for product in produucts %} <div class="col-sm-5 col-lg-5"> <div class="equipmentbox"> <div class="equipmentimgbox"> <img src="{{"**IMAGE URL HERE**"}}"> </div> <a href="">{{ product.product_name }}</a> </div> </div> {% endfor %} {% else %} <div class="col-md-12"> <p>No Products Available</p> </div> {% endif %} Product table contains product details and ProductImage contains images related to particular product. I have a listing page where I wan to display ProductTitle and Image. How can I fetch image from the other table and display it with product title. Thanks in advance. -
Visualize link has been clicked or not
I'm currently working on a web app in which I would like to display to the user whether they have visited the link already or not. The code that displays the links is fairly simple, as seen below. <ul> <li><a href="http://google.com">google</a></li> <li><a href="http://facebook.com">facebook</a></li> <li><a href="http://amazon.com">amazon</a></li> </ul> What I would like is to visualize that a link has been clicked by just adding a checkmark, or something along those lines, to the right of the link. How would I go about doing that? I'm working with Django for this project so a Django-specific solution would be great. -
npx create-react-app command does not work, returns ES module error instead
Here is the command that I ran to try to create a React app and the resulting error log. I have been able to successfully run it three times before with the command $ npx create-react-app, but now every time that I run it, it does not work and instead returns an error related to ES modules. I have been experimenting with many ways to integrate React with Django, but I don't think that I edited any core files in doing so that would have caused this error. I am completely new to React and Node.js so any advice would be greatly appreciated. npx: installed 99 in 7.591s Must use import to load ES Module: /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/index.js require() of ES modules is not supported. require() of /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/index.js from /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/run-async/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/package.json.``` -
using form valid method to acess objects from requests made in django
i'm creating a small web application where users can review cars in my web app i made reviews to be relatable objects to cars and as such each review has a car attribute as a ForeignKey. I went on to make a createview for reviews though with a urlpattern containing a car object id . my goal is to find a way of the review form to know which car i am reviewing just like how i used form valid method to enable the form to grab current user making requests to server my models from django.db import models from django.urls import reverse from categories.models import Category # Create your models here. class Car(models.Model): image = models.ImageField(upload_to='images/cars/') make = models.CharField(null=False, blank=False, max_length=30) model = models.CharField(null=False, blank=False, max_length=30) year = models.IntegerField(null=False, blank=False) transmission = models.CharField(null=False, blank=False, max_length=30) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.model def get_absolute_url(self): return reverse('car_detail', args=[str(self.id)]) from django.db import models from django.urls import reverse from users.models import CustomUser from cars.models import Car # Create your models here. class Review(models.Model): title = models.CharField(max_length=20) description = models.TextField(max_length=160) date_added = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) car = models.ForeignKey(Car, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('review_detail', args=[str(self.id)]) views from … -
Efficient way of avoiding adding duplicate entries to Django model
I've read quite a few posts on how to make a Database/Model unique in Django and it all seems to work. However, I do not see any posts discussing an efficient way of avoiding adding duplicate entries to a database. My model looks like this: # from app.models class TestModel(models.Model): text = models.TextField(unique=True, null=True) fixed_field = models.TextField() The way I currently avoid adding duplicate entries without getting an error is as follows. # from app.views posts = ["one", "two", "three"] fixed_field = "test" for post in posts: try: TestModel(text=post, fixed_field = fixed_field).save() except IntegrityError: pass If I would not do this I would get an IntegrityError. Is there any way I could make this more efficient? -
Parse user input to show as html code. Python + Django
I have Publication class with field for input tags. I capture it with POST method. The problem is that I can not parse it correctly to be able to use those tags as follows {% for item in tags_string %} {{ item.tag }} {% endfor %} How do I format this tags_string so django understands it. I tried to make a QuerySet using next method, and building a list of dictionaries result = [] for a in tags.split(): tag_entry = { 'tag' : a, } result.append(product_entry) As a result I receive a line [{'tag': 'sky', 'tag': 'mountain'}] But my page doesn't show anything using mentioned code block. -
Selenium Webdriver is closing after a while when using Celery
i am new here, im doing an whatsapp bot with django that should be keep running forever to wait for clients chats. The application seems to be running normal when I only use python and run the script. The script starts when I run it by clicking a button on the html form, it gets the interaction preprogrammed from database and start the script to keep waiting new interactions from clients. For this reason, i chose celery to make the script run forever in the backend. The problem is that when sometime pass, it suddenly closes selenium webdriver. PS: i run celery with: celery -A WhatsappBot worker --pool=solo -l info PS2: Im using redis PS3: Im using WINDOWS the logic chain of the app is as follows: 1 - get input from html button. 2 - get interaction information from database. 3 - start a synchronous selenium just to show qr code, when it is scanned, this script ends and it returns the webdriver session and url. 4 - starts the interaction script, connecting remotely to the session got from previous step. after that, when some time pass the celery cmd returns: [2020-04-25 13:47:22,235: WARNING/MainProcess] Retrying (Retry(total=2, connect=None, read=None, redirect=None, … -
How to to access the folder /img in virtual environment with django project?
in virtual environment : virtuelenv, I created a Django project, but when I want to integrate an image in a Template the image doesn't appear. {% extends "base.html" %} {% block title %}Ma page d'accueil{% endblock %} {% block content %} {% load static %} <h2>Bienvenue !</h2> <p> <img src="{% static 'blog/crepes.png' %}" alt="Mon image" /> </p> <a href="/blog/addition/45/52"> Lien vers mon super article N° 42 </a> {% endblock %} please I need your help. Thank you -
Cannot generate django.po files from docker-compose
I'm using Django 3.0.5 inside of a docker-container, linked to an Postgres-container. I would like to generate django.po files but when I'm trying to use this command: docker-compose run web python3 manage.py makemessages -l en I got this error: CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. Meanwhile, when I directly access to my container, it works: (Here, ad2b13f2fe87 is the ID of my django-container) docker exec -it ad2b13f2fe87 bash root@ad2b13f2fe87:/code# gettext --version gettext (GNU gettext-runtime) 0.19.8.1 ... root@ad2b13f2fe87:/src# python3 manage.py makemessages -l en processing locale en Can someone explain me what the issue is? Thank you. -
Django query for many to many relationship to find a user
this is my model: class Student(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) frist_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) father_name = models.CharField(max_length=250) national_code = models.CharField(max_length=12) date_of_birth = models.DateField() phone_regex = RegexValidator(regex=r'(\+98|0)?9\d{9}', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.",) phone_number = models.CharField(validators=[phone_regex], max_length=13, blank=True,help_text='Do like +98913.......') # validators should be a list CHOICES = ( ('male','Male'), ('female','Female') ) gender = models.CharField(choices=CHOICES,max_length=6) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return (self.frist_name) class Classes(models.Model): book = models.CharField(max_length=250) grade = models.CharField(max_length=250) teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE) student = models.ManyToManyField(Student,related_name='student') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.grade how can i make query to find a user book and grade for a specific student? like : the frist name is mohammad and last name is kavosi and username is 0605605605 i want to find the grade and book of this user is my model True or not?