Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save subform in parent form django ModelForm?
I have these models, enter image description here enter image description here with the following forms.py enter image description here I am have subform which is Bill form inside Transaction form, upon submission of transaction form, I want my bill form to be saved as well, please advice here is the view im trying enter image description here -
GenericRelation: You might need to add explicit type casts
I have a model Link: class Link(models.Model): tags = TaggableManager(through=LinkTag) actions = GenericRelation( Action, related_query_name='link', content_type_field='action_object_content_type', object_id_field='action_object_object_id', ) The Action model is here. I need to find all actions on links with tag "test1": tag=Tag.objects.filter(name="test1").first() Action.objects.filter(link__tags__name__in=[tag]) # also tried with: Action.objects.filter(link__tags__name__in=[tag.name]) However, this gives an error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: operator does not exist: character varying = integer LINE 1: ... ON ("actstream_action"."action_object_object_id" = "links_l... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return … -
What is the most simple solution to run python script in the background in Django
What I need I have a Django project. And it has one python script that need to be run in the background I used supervisor for this. But now I need to add to buttons in the admin: Start. This button should run the script in the background Stop. This button should stop the script Problem What is the best way to run my script in the background. I have read some articles about background jobs in Django. And they say the best way to do it is Celery + Redis. But I think that Celery is to complex for this small task and there should be some other solution, some simple solution Question What is the best simple solution to run and stop my script with 2 buttons in the Django admin? -
Django Update of table doesn't work because of clean method in modelForm
Here is my form class TypeCompteForm(forms.Form): LIBELLES = (("xxxxx","xxxxxxx"),("xxxxxxxx","xxxxxxxxxx")) libelle = forms.ChoiceField(required=True,choices=LIBELLES,error_messages=err_msg,widget=forms.Select(attrs={"class":"form-control","placeholder": "Libellé du type"})) code = forms.CharField(required=True, max_length=50,widget=forms.TextInput(attrs={"class":"form-control","placeholder": "Code de du type"})) def clean_libelle(self): data = self.cleaned_data["libelle"] if TypeMagasin.objects.filter(libelle=data).exists(): raise ValidationError("Un type de magasin avec ce libellé existe déjà !") return data With this form I manage to insert the data in the data base. But when I try to modify one record the clean_libelle method executes. Below is the view I use for updating def updateView(request,id): instance = MyModel.objects.get(pk=id) form = ModelForm(instance=instance) if request.method == "POST": form = ModelForm(request.POST, instance=instance) if form.is_valid(): form.save() else: print(form.errors) return render(request,"template.html") return render(request,"reconciliation/template.html",{"form":form}) -
I would like csv file to update the information in existing field django
I have uploaded csv file through POST method in django but unable to store csv file filed in the existing field. i mean to say already table record in db. username, userpassword, urloc, scode. i would like to check if scode value and positing csv scode value equal then only update the record. views.py if request.method == 'POST': # up = request.FILES.get('uploadfile', '') csv_file = request.FILES.get('uploadfilec', '') print(csv_file) # lets check file is csv or not if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') # set up a stream which is when we loop through each line we are able to handle a data in stream io_string = io.StringIO(data_set) print(io_string) next(io_string) cy = EmailDb.objects.all() for column in csv.reader(io_string, delimiter=',', quotechar="|"): # pt = EmailDb.objects.all().filter(scode=column[3]).values_list('scode', flat=True) # for i in pt: # print(i) # print('don') # print(pt) for i in cy: co = i.scode print("co",co) print("column",column[3]) if co == column[3]: _, created = EmailDb.objects.all().filter(scode=column[3]).update( useremail = column[0], userpassword = column[1], urloc = column[2], scode = column[3] ) return render(request, 'NEC/crupload.html') -
error 'function' object has no attribute 'objects' when i try to create a record in the model in veiws.py
I want to create a record in the register model immediately after creating user But unfortunately, an error 'function' object has no attribute 'objects' shows me views.py code: from django.shortcuts import render,redirect from .forms import userregister from django.contrib.auth.models import User from testapp.models import register def register(request): if request.method == 'POST': form = userregister(request.POST) if form.is_valid(): cd = form.cleaned_data User.objects.create_user(cd['username'],cd['email'],cd['password']) register.objects.create(address='NONE' , phone = 'NONE' ,username_id= cd['id']) return redirect('testapp:index') else: form = userregister() context = {'form' : form} return render(request,'register.html',context) models.py code from django.db import models from django.contrib.auth.models import User class register(models.Model): address = models.CharField(max_length=200) phone = models.CharField(max_length=11) username = models.OneToOneField(User,on_delete = models.CASCADE) def __str__ (self): return str(self.username) I want to create a record in the register model immediately after the user is added, with the value NONE and the foreign key should be the same user as the one created now. -
Django login authentication always returns none
I am using django contrip auth for authenticate user. Signup function always working and register and login user successfully but after that I m logged out and try to login again but this time login function doesnt work. I add this codes my settings file AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) AUTH_USER_MODEL = 'app.User' My User model seems like that in models.py class User(AbstractUser): pass My Login and Register function def dlogin(request): if request.method=='GET': return render(request, "login.html") if request.method == "POST": username = request.POST['username'] password = request.POST['password'] # Attempt to sign user in user = authenticate(request, username=username, password=password) print(user) # Check if authentication successful if user is not None: login(request, user) cur_user = request.user return render(request,'index.html',{ 'success':'login successful', 'user':cur_user }) else: return render(request,'login.html',{ 'error':'Invalid username and/or password.' }) @csrf_exempt def signup(request): if request.method != "POST": return render(request, 'signup.html') # Get form information username = request.POST["username"] password = request.POST["password"] confirmation = request.POST["confirmation"] # Ensure password matches confirmation if password != confirmation: return render(request,'register.html',{ 'message':'Passwords dont match' }) # Attempt to create new user user = User.objects.create_user(username,password) user.save() login(request, user) return redirect('index') I did some research and couldn't find any problem in my code. Does anyone can help me? -
Page not found After using UpdateView class
I have a project that requires an update form, I am using the Django generic views, specifically the UpdateView. I Think this is an error with the URL, but I dont find where it is. Eror also refers to the url The current path, actualizar_empleado/, didn’t match any of these. My code is the following: Views.py `from django.shortcuts import render, get_object_or_404 from django.views.generic import ( CreateView, DetailView, ListView, UpdateView, ListView, DeleteView ) from . models import EmployeesInfo from . forms import EmployeeForm class EmployeeCreate(CreateView): form_class = EmployeeForm template_name = 'employeeCreate.html' success_url = '/lista_empleados/' def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) class EmployeeList(ListView): model = EmployeesInfo template_name = 'employeeList.html' success_url = 'lista-empleados/exitoso' class EmployeeDetail(DetailView): model = EmployeesInfo template_name = 'employeeDetail.html' success_url = 'detalle-empleado/exitoso' def get_object(self): id_ = self.kwargs.get("pk") return get_object_or_404(EmployeesInfo, pk=id_) class EmployeeUpdate(UpdateView): form_class = EmployeeForm queryset = EmployeesInfo.objects.all() template_name = 'employeeUpdate.html' success_url = '/listaempleados/' def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) def get_object(self): id_ = self.kwargs.get("pk") return get_object_or_404(EmployeesInfo, pk=id_)` -
After submitting data to server, redirect to specific part of page?
I want to redirect to specific part of page after submitting data to server not to default view of current page instead when I am working on section plan for growth and I am working of this part of page if I submit the data from this part after I submit the data to server I want to be in this section which by default it shows me the introduction section and I don't want this. Is there any solution to this? I want to stay in section plan for growth when I submit the data. -
is there a way for me to merge two Django functions calls?
I'm trying to merge two python functions, with their corresponding AJAX JS requests. So, I have two JS functions that call two different views. I need to merge everything in aa single request to optimise server's trafic. <script> $(document).ready(function() { function imgMarkup(model) { if (model.media) {//mediasrc return `<img class='imgchat' src=${window.location.origin}/static/${model.mediasrc}.png>` } return ''; } function csvMarkup(model) { if (model.excel) { return `<p><a href="${window.location.origin}/static/${model.mediasrc}" class="dl-csv">[Download]</a></p>` } return ''; } function botCheck(model) { if (model.bot) { return 'gpt.jpeg' } return 'user.jpeg'; } setInterval(function() { $.ajax({ type: 'GET', url: "/checkview", success: function go(response) { console.log(response); $("#display").empty(); for (var model of response.models_to_return) { let botclass = model.bot ? 'right' : ''; const temp = ` <div class='chat-c ${botclass}'> <div class=" picture-c"><img src="${window.location.origin}/static/AAA/${botCheck(model)}" class="picture"></div> <div class='chat'> <p class='${botclass} p-chat'>${model.room}</p> ${imgMarkup(model)} ${csvMarkup(model)} </div> </div>`; $("#display").append(temp); $('#screen').css({ 'display': 'none', }); } }, error: function(response) { //alert('An error occured') } }); }, 10000); }) </script> <script> $(document).ready(function() { setInterval(function() { $.ajax({ type: 'GET', url: "/workspace", success: function check(response) { console.log(response); $("#variat").empty(); for (var model of response.memory_return) { const temp = ` <span class='a-items'>${model.date1} : ${model.date2}</span> <span class='a-items'>${model.symbols}</span>`; $("#variat").append(temp); } }, error: function(response) { //alert('An error occured') } }); }, 10000); }) </script> And their corresponding views.py: Python: def … -
Django ORM JOIN of models that are related through JSONField
If I have 2 models related through ForeignKey I can easily get a queryset with both models joined using select_related class Foo(Model): data = IntegerField() bar = ForeignKey('Bar', on_delete=CASCADE) class Bar(Model): data = IntegerField() foos_with_joined_bar = Foo.objects.select_related('bar') for foo in foos_with_joined_bar: print(foo.data, foo.bar.data) # this will not cause extra db queries I want to do the same thing but in the case where Foo keeps it's reference to bar in a JSONField class Foo(Model): data = IntegerField() bar = JSONField() # here can be something like {"bar": 1} where 1 is the ID of Bar class Bar(Model): data = IntegerField() foos_with_joined_bar = ??? Is it possible to get foos_with_joined_bar in this case using Django ORM? P.S. We're not discussing the reasoning behind storing foreign keys in the JSONField, of course it's better to just use ForeignKey. -
What I have to learn Flutter or React Native?
I have learned Django and HTML, CSS, and Bootstrap for web Development but now I want to learn App Development also, I am confused about what I have to choose with Django, whether I have to learn Flutter or React Native or something else give I have knowledge of OOP as well as Front End HTMl CSS and Bootstrap -
ImportError: libstdc++.so.6: cannot open shared object file: No such file or directory
I am trying to deploy my Django project that uses React on the frontend inside Django app to railway. The app was deployed on Heroku before but after adding a whisper package from openAI the slug size became too big to use it there so I opted to use railway instead. I have another Django project with React running there so the problem comes from the packages. The problem comes from package called gpt-index which uses pandas package and that's where the error occurs. What can I do to fix this? Nix-packs setup: [phases.setup] nixPkgs = ['nodejs-16_x', 'npm-8_x ', 'python310', 'postgresql', 'gcc '] [phases.install] cmds = ['npm i ', 'python -m venv /opt/venv && . /opt/venv/bin/activate && pip install -r requirements.txt'] [phases.build] cmds = ['npm run build'] [start] cmd = '. /opt/venv/bin/activate && python manage.py migrate && gunicorn backend.wsgi' Full traceback: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/opt/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/opt/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/venv/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/opt/venv/lib/python3.10/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/nix/store/al6g1zbk8li6p8mcyp0h60d08jaahf8c-python3-3.10.9/lib/python3.10/importlib/__init__.py", line … -
Return all active comment in a post
i have this blog site,i want to return all acvtive comments associated to a post. def post_detail(request,year, month,day, post): post = get_object_or_404(Post,status=Post.Status.PUBLISHED,slug=post,publish__year=year,publish__month=month,publish__day=day) #list of active comments for this post comments = post.comments.filter(active=True) #form for users to comment form = CommentForm() #List of similar posts post_tags_ids = post.tags.values_list('id',flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) [:4] return render(request,'blog/post/detail.html',{'post':post,'comments':comments,'form':form}) Its returning null response, -
I cannot post comment in Django, no error
I'm working on a Django blog and I'm stuck here... I want to post comment and when I do that it just refresh the page and nothing happens. I have no idea where I'm making a mistake, please see my code below: this is views.py def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) related_posts = post.tags.similar_objects()[:3] comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': if request.user.is_authenticated: comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.author = request.user new_comment.save() else: messages.warning(request, 'You need to be logged in to add a comment.') else: if request.user.is_authenticated: comment_form = CommentForm(initial={'author': request.user}) else: comment_form = CommentForm() context = {'post': post, 'related_posts': related_posts, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form} return render(request, 'post_detail.html', context) this is comment part post_detail.html {% if user.is_authenticated %} <!--comment form--> <div class="comment-form"> <h3 class="mb-30">Leave a Reply</h3> <form class="form-contact comment_form" action="{% url 'post_detail' post.slug %}" method="post"> {% csrf_token %} <div class="row"> <div class="col-12"> <div class="form-group"> {{ comment_form | crispy }} </div> </div> </div> <div class="form-group"> <button type="submit" class="button button-contactForm">Post Comment</button> </div> </form> </div> {% else %} <div class="alert alert-danger" role="alert"> Please log in to post a comment. </div> {% endif %} this is models.py class Comment(models.Model): post = models.ForeignKey(Post, … -
Django Nested formsets for models
I'm writing a program to store analyses for patient and I need to make a form with nested forests with next scheme Each patient has an analyses results sheet Each result sheet has date, patient (foreign key) and set of analyses values Each set of analyses values has strict number and strict types of analyses Each type of analyse has it's value, name and units For example I want to create John's analyse result sheet for blood Patient: John Date: 10.02.23 Set of values: 'Blood analysis' Red blood cells: 3,23 10^9 Haemoglobin: 124 g/l I've made models patient/models.py class Patient(models.Model): hist_number = models.IntegerField(unique=True, verbose_name='Номер истории болезни') last_name = models.CharField(max_length=32, verbose_name='Фамилия') analysis/models.py class PatientAnalysisResultSheet(models.Model): an_number = models.PositiveBigIntegerField(verbose_name='Номер исследования', unique=True) date = models.DateField(verbose_name='Дата анализа') time = models.TimeField(verbose_name='Время') patient = models.ForeignKey('patient.Patient', verbose_name='Пациент', on_delete=models.CASCADE) class AnalysisType(models.Model): name = models.CharField(max_length=256, verbose_name='Исследование', unique=True) measurement = models.CharField(max_length=10, verbose_name='Единицы измерения') class PatientAnalysis(models.Model): sheet = models.ForeignKey(PatientAnalysisResultSheet, on_delete=models.CASCADE) analysis = models.ForeignKey(AnalysisType, verbose_name='Лабораторный показатель', on_delete=models.CASCADE) value = models.FloatField(verbose_name='Значение') So I googled about formsets and now did next steps: views.py from django.contrib import messages from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import FormView # Create your views here. from django.views.generic.detail import SingleObjectMixin from analysis.forms import PatientAnSheetFormset from patient.models import … -
Cannot assign "'cool_username'": "Comment.author" must be a "User" instance?
I'm working on a Django blog and I'm stuck here... I'm getting this error Cannot assign "'cool_username'": "Comment.author" must be a "User" instance. I have no idea where I'm making a mistake, please see my code below: this is views.py def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) related_posts = post.tags.similar_objects()[:3] comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': if request.user.is_authenticated: comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.author = request.user new_comment.save() else: messages.warning(request, 'You need to be logged in to add a comment.') else: if request.user.is_authenticated: comment_form = CommentForm(initial={'author': request.user}) else: comment_form = CommentForm() context = {'post': post, 'related_posts': related_posts, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form} return render(request, 'post_detail.html', context) this is comment part post_detail.html {% if user.is_authenticated %} <!--comment form--> <div class="comment-form"> <h3 class="mb-30">Leave a Reply</h3> <form class="form-contact comment_form" action="{% url 'post_detail' post.slug %}" method="post"> {% csrf_token %} <div class="row"> <div class="col-12"> <div class="form-group"> {{ comment_form | crispy }} </div> </div> </div> <div class="form-group"> <button type="submit" class="button button-contactForm">Post Comment</button> </div> </form> </div> {% else %} <div class="alert alert-danger" role="alert"> Please log in to post a comment. </div> {% endif %} this is models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') body = models.TextField() … -
Django user permission by branch
If there is user belong to branch_1 and branch_2 but with different role/group in branch_1 he is HR manager but in branch_2 he is HR lets say with no edit permission or receives employee emails. I don't think its correct to create group or permissions for branch_1 and group for second one, and so on for every new relation between an user and a branch. branch a group should be abstract from that. What is the best approach to manage user permission per branch? Thank you. -
cs50 network javascript fetch
I'm stack with showing the like or unlike button and the likes number without refreshing the page, i should do it with javascript fetch call. Any idea how to solve it. This is my codes: class Like(models.Model): user_like = models.ForeignKey( User, on_delete=models.CASCADE, related_name="like_user") post_like = models.ForeignKey( NewPost, on_delete=models.CASCADE, related_name="like_post") def __str__(self): return f"{self.user_like} likes {self.post_like}" class Post(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="author", blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) post = models.TextField(max_length=200, blank=True, null=True) liked = models.ManyToManyField(User, default=None, blank=True) def __str__(self): return f"{self.post}" def like(request, post_id): """ Set liked """ post = Post.objects.get(pk=post_id) user = User.objects.get(pk=request.user.id) if user in post.liked.all(): post.liked.remove(user) else: post.liked.add(user) like = Like(user_like=user, post_like=post) like.save() return JsonResponse({"likes": post.liked.all().count()}) <h6 class="card-subtitle mb-2 text-muted" id="count-likes">({{ post.liked.all.count }}) Likes</h6> <button type="submit" id="like-btn" class="btn btn-outline-info"> {% if user not in post.liked.all %} Like {% else %} Unlike {% endif %} </button>``` -
Django media file page not found
So, I'm trying to follow Django documentation about the static files and media files I have a clean Django installation and I want to add the media folder. What I've done? I've changed the urls.py inside the project (not the app) and the settings.py as below settings.py STATIC_URL = 'static/' MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / "media" STATICFILES_DIRS = [ BASE_DIR / "static", ] urls.py urlpatterns = [ path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But I got the Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in web_project.urls, Django tried these URL patterns, in this order: admin/ ^media/(?P.*)$ The empty path didn’t match any of these. I've also tried adding the 'django.template.context_processors.media' into TEMPLATES and using os as below STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) but nothing changes What it could be? -
Django - How to get just two fields from foreigKey in DRF model/serializer
Here is my model and serializers classes: class Employee(models.Model): name = models.CharField(max_length=255) manager = models.ForeignKey('self', on_delete=models.RESTRICT, related_name='employee_manager') score = models.FloatField() updator = models.ForeignKey(User, on_delete=models.RESTRICT, related_name='employee_updator') class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' Currently I'm getting this response: [ { "id":1, "name": "David", "manager": null, "score": 18.7, "updator": 15 }, { "id":2, "name": "Sara", "manager": 1, "score": 12.3, "updator": 15 } ] But I need to have 'id' and 'name' of manager like this: [ { "id":1, "name": "David", "manager": null, "score": 18.7, "updator": 15 }, { "id":2, "name": "Sara", "manager": { "id":1, "name":"David" }, "score": 12.3, "updator": 15 } ] I tried adding 'depth=1' to my serializer but it also returns 'employee_updator' details that I'm not interested in. Any help would be appreciated. Thanks. -
How do I get data from a form in django while the user is filling it out and show hidden fields
I'm having problems when getting data being filled in a form in django I'm wanting to create a form with hidden fields, but which are dependent on another field. If the previous field has been filled in, the hidden field is shown. -
How to use --rebuild correctly in Django+elasticsearch?
I have a table in my db which size is about 75 millions of records im trying to use command python manage.py search_index --rebuild But its finished after about 3 hours with exception django.db.utils.OperationalError: server closed the connection unexpectedly even when i use --parallel arg, so is there exists a way to rebuild an index? I wanna note that i do it locally not on server, just to test is it speeds up my search or not. And i also use django signals to update the index when the table updates, so this action will take so much time as well? -
"Relay access denied" in django app using namecheap private email
So I have a Django app that sends confirmation emails to users who want to register their account. It looks something like this views.py def send_activation_email(user, request): current_site = get_current_site(request) email_subject = "Activation Email" context = {"user": user, "domain": current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': generate_token.make_token(user) } email_body = render_to_string('email/activate.html',context) email = EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email]) email.send() and with settings.py looking like this EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.privateemail.com' EMAIL_FROM_USER = 'verification@ianisdo.xyz' EMAIL_HOST_PASSWORD = '[redacted]' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False The problem is that, when I try to send a email when the user creates an account, I get this error SMTPRecipientsRefused at /register/ {'ianis.donica@gmail.com': (554, b'5.7.1 <ianis.donica@gmail.com>: Relay access denied')} What I know for sure is: that it's not a problem with the private namecheap email, from which I can still send emails just not from my website. I also know the problem is not due to gmail not liking my email, as the same error when the email is sent to a yahoo.com domain. I also know that the issue is not with the settings.py not connecting to the views.py I also know that all the details are entered correctly From my knowledge and talking to … -
ImportError: cannot import name 'views' from 'bot'
I'm trying to implement a bot into a website using django and I ran into the error above. this is how the directory looks like: directory this is the urls for chatbot from . import views from django.urls import path urlpatterns = [ path('chatbot/', views.chatbot_view, name='chatbot'), path('chatbot/', views.chatbot, name='chatbot'), ] and this is the views for chatbot from django.shortcuts import render from . chatbot import create_connection from . chatbot import close_connection from . chatbot import execute_query from . chatbot import add_answer from . chatbot import normalize_text from . chatbot import get_keywords from . chatbot import match_question from . chatbot import get_answer from . chatbot import add_greeting_answers from . import chatbot_script def chatbot_view(request): if request.method == 'POST': question = request.POST['question'] answer = chatbot_script.get_answer(question) return render(request, 'chatbot/chatbot.html', {'answer': answer}) else: return render(request, 'chatbot/chatbot.html') I have modified the views and urls in the directory of chatbot and when I try to modify the urls for the directory bot this is what happens: error image I tried copying the views file from chatbot to bot and make changes to the urls in bot hoping that would make it work rather than say page not found.