Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: Object of type Decimal is not JSON serializable | Django
I am getting quite unusual error. I got pretty confused because of this. When I iterate over the cart items and try to view them it throws a TypeError Object of type Decimal is not JSON serializable. But if i remove the block from my templates then refresh the page and again add the same block to my templates and refresh the page it works. I have added some screenshots. Please have a look and help me out with this cart.py class Cart(object): def __init__(self, request): """ Initialize the cart """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = { 'quantity': 0, 'price': str(product.price) } if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def __iter__(self): """ Iterate over the items in the cart and get the products from the database """ product_ids = self.cart.keys() # get the product objects and add the o the cart products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in … -
Reading content of docx and save in models.TextField()
I am trying to receive a docx file from user in django, open it, and copy all its content (containing just text and mathematical equations) into textBody of my model. In the model.py I have class myWordFileContent(models.Model): textBody= models.TextField() and in view.py I have def receive_reports(request): if request.method == 'POST': myFile = request.FILES['UserFile'] tempBody= [''] for chunk in myFile.chunks(): tempBody.append(chunk) record = myWrodFileContent.objects.create(textBody= tempBody) return render(request, 'testPage.html') but when I save a docx file content, and go to my model table in admin page I have [",44, 141, 143, 152, 136, 27, 152, 131, 227, 45, 160, 198] Whats wrong? how can I do this to have correct text? -
Mypy linting in VSCode Errors out with "Error constructing plugin instance of NewSemanalDRFPlugin"
Trying to run Mypy linter in VSCode, always getting the same error in the output... ##########Linting Output - mypy########## Error constructing plugin instance of NewSemanalDRFPlugin mypy==0.770 mypy-extensions==0.4.3 django-stubs==1.5.0 djangorestframework-stubs==1.2.0 python3.8.5 Django with DRF -
django - sending email with gmail failure
I'm trying to implement an automatic email sending system with gmail on my django app. This is my view: from .forms import EmailPostForm from django.core.mail import send_mail def post_share(request, post_id): #retrive post by # post = get_object_or_404(Post, id=post_id, status='published') sent=False if request.method == 'POST': # Form was submitted form = EmailPostForm(request.POST) if form.is_valid(): # Form passes validation cd = form.cleaned_data #...send Email post_url = request.build_absolute_uri(post.get_absolute_url()) subject = f"{cd['name']} recomends you read {post.title}" message = f" Read {post.title} at {post_url}\n\n" \ f" {cd['name']}\s comments: {cd['comments']}" send_mail = (subject, message, 'my_gmail_acccount@gmail.com', [cd['to']]) sent=True else: form = EmailPostForm() context = { 'form':form, 'post':post, 'sent': sent } return render(request, 'byExample_django3/post/share.html', context) and my form: from django import forms class EmailPostForm(forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() comments= forms.CharField(required=False, widget=forms.Textarea) and my template: {% extends "byExample_django3/base.html" %} {% block title %}Share a post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully sent</h1> <p> "{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}. </p> {% else %} <h1>Share "{{ post.title }}" by e-mail</h1> <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Send e-mail"> </form> {% endif %} {% endblock %} and my url: path('<int:post_id>/share', views.post_share, name='post_share') … -
How can make dynamic id in script with django
I want change js-lightgallery id name to photos name and I change this codes id js-lightgallery make dynamic var $initScope = $('#js-lightgallery'); Gallery.html <div id="js-lightgallery"> {% for photo in post %} {% if photo.ders == a %} {% if photo.img %} <a class="jg-entry entry-visible" href="{{photo.img.url}}" data-sub-html="{{photos.title}}"> <img class="img-responsive" src="{{ photo.img.url }}" alt="{{photo.title}}"> </a> {% endif %} {% endif %} {% endfor %} Script var $initScope = $('#js-lightgallery'); -
How long does it take for Google to change redirect uri to be reflected on django website?
I have setup a redirect uri for a Google API, since I have changed the redirect uri I get an error response that the redirect uri is mismatched. In the google developer console I see the updated redirect uri but when I try to socially authenticate the django website again and I see that the redirect_uri is still referring to the old one(that no longer exists in credentials redirect url ) that i afterwards updated. So my question is, how long does it take before my changed redirect uri is active? i have restarted the server and cleared all cached files but still when i try to socially authenticate through google+ api it is still redirecting to that old uri with the redirect_uri_mismatch error. and i am using social-auth-django-app for social authentication. please help me and thanks in advance. -
django sitemap.xml documentation contradicts with the original sitemap documetation
I'm creating a sitemap for my django project using the built-in site framework. By default, without any custom/configuration, I got this kind of sitemap: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://example.com/</loc> <lastmod>2020-07-29</lastmod> <changefreq>hourly</changefreq> <priority>0.8</priority> </url> <url> <loc>https://example.com/subdomain/</loc> <lastmod>2020-07-29</lastmod> <changefreq>hourly</changefreq> <priority>0.8</priority> </url> </urlset> Well, this is where I started shruging. Quoting from django's sitemap documentation: location Optional. Either a method or attribute. If it’s a method, it should return the absolute path for a given object as returned by items(). If it’s an attribute, its value should be a string representing an absolute path to use for every object returned by items(). In both cases, “absolute path” means a URL that doesn’t include the protocol or domain. Examples: Good: '/foo/bar/' Bad: 'example.com/foo/bar/' Bad: 'https://example.com/foo/bar/' But as you can see from the example above, by default the protocol and the domain are both included inside loc tag on the sitemap.xml. Quoting from the Sitemap Documentation that are contradicts with each other: <loc> required URL of the page. This URL must begin with the protocol (such as http) and end with a trailing slash, if your web server requires it. This value must be less than 2,048 characters. So, assuming I'm doing SEO and trying to … -
Get Foreign Key Values from Django ListView with if Statement
I have two related models and need to get data from both tables. I get all foreign key values when I write a simple forloop, but when I use if statement it doesn't work. I have to say that the if statement works fine for non-foreign key fields. here are my codes: models.py: class EquipmentGroup(models.Model): EQUIPMENT_GROUPS = ( ('Bottomhole Assemblies','Bottomhole Assemblies'), ('Rig Equipment','Rig Equipment'), ('Surface Equipment','Surface Equipment'), ('Subsurface Equipment','Subsurface Equipment'), ('Completion Tools','Completion Tools') ) equipment_group = models.CharField(max_length=64,choices = EQUIPMENT_GROUPS) def __str__(self): return (self.equipment_group) class EquipmentType(models.Model): equipment_group = models.ForeignKey(EquipmentGroup,on_delete=models.CASCADE, related_name='eqpgroup_in_eqptype') equipment_type = models.CharField(max_length = 128) def __str__(self): return str(self.equipment_group) views.py: class BtmAssyListView(LoginRequiredMixin, ListView): login_url = '' redirect_field_name = 'redirect_to' context_object_name = 'btm_assy_list' template_name='management/templates/management/btm_assy.html' model = EquipmentType template: {%for i in btm_assy_list %} {%if i.equipment_group == "a record from equipment_group" %} {{i.equipment_type}} {%endif%} {%endfor%} The above code in the template doesn't work but as I explained when I use the following code it works: {%for i in btm_assy_list %} {%if i.equipment_type == "a record from equipment_type" %} {{i.equipment_group}} {%endif%} {%endfor%} -
KeyError in Django Form
When I submit the form I get a Key error, before it was not saving it. I read some answers here about key error but I could not find the problem. Could somebody help me, please? in HTML <h1>Create New Page:</h1> <form action="{% url 'create' %}" method="post"> {% csrf_token %} {{ form.as_p}} <button id='saveButton' >Save!</button> </form> in Vews: class NewEntryForm(forms.Form): title = forms.CharField(label="Title") Content = forms.CharField(widget=forms.Textarea) def create(request): if request.method == "POST": form = NewEntryForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title,content) else: return render(request, "encyclopedia/create.html",{"form": form }) else: return render(request, "encyclopedia/create.html",{"form": NewEntryForm() }) -
Django block content not working - Cant seem to make it work even after looking at some other solutions
I'm doing some small course "Django for beginners", no point to say I'm like a super beginner. I understand the concept of block content and templates. But for one bizarre reason, I can not make block content work and as such, I'm basically stuck. I looked through a lot of similar issues on this page but I guess I'm really missing something. I have this really simple base html which is saved in a folder "templates" <!doctype html> <html> <head> <title>Base title</title> </head> <body> {% block content %} replace me {% endblock %} </body> </html> And I create a contact html also saved in my folder "templates" {% extends 'base.html' %} {% block content %} {% endblock %} In my settings I have defined the templates DIRS as such TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] And my urls.py are set like this from django.contrib import admin from django.urls import path from Pages.views import home_view, contact_view, about_view, social_view urlpatterns = [ path('',home_view, name = 'home'), path('contact/',contact_view), path('about/',about_view), path('social/',social_view), path('admin/', admin.site.urls), ] I know that the contact pages does use the base.html pages because when … -
DRF, return serialized data after update object in the view
I have the following view with custom create method that can post or patch data: class MonthsViewSet(ModelViewSet): authentication_classes = (TokenAuthentication,) def get_queryset(self): # TODO: Workaround until Auth is setup on the front. query_set = Month.objects.all() if isinstance(self.request.user, AnonymousUser) \ else Month.objects.filter(farm__user=self.request.user) return query_set serializer_class = MonthSerializer def create(self, request, *args, **kwargs): request_month = request.data['month'] year = request.data['year'] farm = request.data['farm'] days = request.data['days'] # TODO: understand why built-in update_or_create didn't work here. farm_obj = Farm.objects.get(id=farm) try: month = Month.objects.get(year=year, month=request_month, farm=farm_obj) month.days = days month.save() serializer = MonthSerializer(data=month, many=False, partial=True) serializer.is_valid(raise_exception=True) return Response(data=serializer.data, status=status.HTTP_200_OK) except Month.DoesNotExist: Month.objects.create(year=year, month=request_month, farm=farm_obj, days=days) return Response(status=status.HTTP_201_CREATED)` Now my problem is sending back the object's data after updating, the update is successful but I can't serialize that object after saving it and sending it back in the response when a request to update a month comes in, it gets updated but the response is this error: 400 Error: Bad Request [ { "non_field_errors": [ "Invalid data. Expected a dictionary, but got Month." ] } ] My serializer: class MonthSerializer(serializers.ModelSerializer): class Meta: model = Month fields = '__all__' -
Getting SynchronousOnlyOperation error Even after using sync_to_async in django and discord.py
I am trying to make a discord bot for a Django website. While going to implement I came to know that Django database doesn't allow asynchronous operation, we must use thread or sync_to_async. I used sync_to_async and it seemed to work. But then I run into a problem, I can't even figure out what is wrong with it and what is going on there. Can anyone explain what I am doing wrong there and what is going on there? @sync_to_async def get_customer(id): try: return Customer.objects.get(discord_id=id) except: return None #------ @bot.command() async def categories(ctx): customer = await get_customer(ctx.author.id) #this line of code works well categories = await sync_to_async(Category.objects.all().filter)(customer=customer) print(categories) #problem is in the line embed = Embed(title='', description="{}".format('\n'.join([ x.name for x in categories]))) await ctx.send(embed=embed) The traceback error I am getting is Ignoring exception in command categories: Traceback (most recent call last): File "/Users/rhidwan/Desktop/personal_transaction/venv/lib/python3.7/site-packages/discord/ext/commands/core.py", line 83, in wrapped ret = await coro(*args, **kwargs) File "discord_bot.py", line 76, in categories print(categories) File "/Users/rhidwan/Desktop/personal_transaction/venv/lib/python3.7/site-packages/django/db/models/query.py", line 252, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/Users/rhidwan/Desktop/personal_transaction/venv/lib/python3.7/site-packages/django/db/models/query.py", line 276, in __iter__ self._fetch_all() File "/Users/rhidwan/Desktop/personal_transaction/venv/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/rhidwan/Desktop/personal_transaction/venv/lib/python3.7/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/Users/rhidwan/Desktop/personal_transaction/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1150, … -
Is there a way to render a template from a template in Django?
I am new to django framework and learning along with my project. I am rendering a homepage from my Django views and there is a hyperlink in the homepage which should redirect to another template and call another view function. The another view function will be called and render the json data to the template. However i am not able to do so. Please suggest how to render another template and call view function from a template or is there any other way around it? -
How to Import from Import-Export Django with choices?
I have a model: class Student(models.Model): TITLE = ( ('Title_Mr', ('Mr')), ('Title_Ms', ('Ms')), ) Name = models.CharField(max_length = 25, default = '') Title = models.CharField(max_length = 32, choices = TITLE, blank=True, null = True) ... with choices and with the Import-Export feature, I want to import students, who have "Mr" or "Ms" as title values. What I tried was from this answer Django import-export choices field but apparently this is for exporting? What to do if I want to import it. Here is my resources.py from import_export import resources, fields from main.models import Schulungsteilnehmer class StudentsResource(resources.ModelResource): Title = fields.Field(attribute='get_Title_display', column_name=('Title')) class Meta: model = Student exclude=('id',) import_id_fields = ('StudentID',) how can I save the values as choice selection values? -
Is there a way to automatically generate objects in a Django Model?
I am making a model that generates 100 code automatically as a task -
How to convert a base64 byte to image in python
I am facing a problem in converting base64byte to image.I tried this filename="chart.png" with open(filename, "wb") as f: f.write(base64.decodebytes(data)) where the base64byte is sored in data (like this b'iV.....'.after this i tried uploading the "filename" to my django database by doing gimage.objects.create(name='Rufus5', pic1=filename) .this creates an empty file chart.png in my django database. -
Heroku-Django: code=H14 desc:"No web processes running"
Heroku logs I am trying to deploy a django app on heroku, this is my first app which I am deploying on heroku, the build succeeded but when I run the URL, It says application error and logs shows following thing. 2020-07-29T07:58:24.000000+00:00 app[api]: Build started by user ketanpatil3106@ gmail.com 2020-07-29T07:58:59.203607+00:00 app[api]: Deploy 26b25759 by user ketanpatil310 6@gmail.com 2020-07-29T07:58:59.203607+00:00 app[api]: Release v6 created by user ketanpatil 3106@gmail.com 2020-07-29T07:59:07.261443+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=newtonnation.herokuapp.com request_i d=debda95e-c51d-4090-87a9-73102c5c9411 fwd="106.193.222.48" dyno= connect= servi ce= status=503 bytes= protocol=https 2020-07-29T07:59:09.000000+00:00 app[api]: Build succeeded 2020-07-29T07:59:10.136919+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=newtonnation.herokuapp.co m request_id=50db9f9b-2e03-4465-b3ba-f851612f3db8 fwd="106.193.222.48" dyno= con nect= service= status=503 bytes= protocol=https 2020-07-29T07:59:12.539684+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=newtonnation.herokuapp.com request_i d=22f644fb-4d6f-48ed-a34f-f35d5dd41033 fwd="106.193.222.48" dyno= connect= servi ce= status=503 bytes= protocol=https 2020-07-29T07:59:13.903721+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=newtonnation.herokuapp.co m request_id=3dfff95c-dd3c-4590-ad22-2c673a9ec5b9 fwd="106.193.222.48" dyno= con nect= service= status=503 bytes= protocol=https 2020-07-29T08:04:38.784712+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=newtonnation.herokuapp.com request_i d=6e61e063-8575-4236-9d87-a1af42058b82 fwd="106.193.222.48" dyno= connect= servi ce= status=503 bytes= protocol=https 2020-07-29T08:04:41.381297+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=newtonnation.herokuapp.co m request_id=ab3bd0e2-5396-4c63-9735-9d0a30f54013 fwd="106.193.222.48" dyno= con nect= service= status=503 bytes= protocol=https Procfile: web gunicorn PHYSICS_COMMUNITY.wsgi … -
Dynamic consuming of web API in Django based on user's choice
The program I am trying to write requires that whenever the user changes a value in a form on Django website, that value will be written to the variable and then inserted into the API's url as parameter inside requests.get() function in views.py file. So basically my Django website is to consume web API. API returns different data sets depending on the explicit endpoint. It can change dynamically depending on what the user chooses in a form, and then, if submit button is clicked, show the content on a django website immediately. Here is the Web API which I use to get data sets: http://api.nbp.pl/en.html forms.py: from django import forms class DateInput(forms.DateInput): input_type = 'date' class ExampleForm(forms.Form): my_date_field = forms.DateField(widget = DateInput) views.py: from django.shortcuts import render import requests from .forms import ExampleForm def home(request): submitbutton = request.POST.get("submit") # I check if submit button is clicked form = ExampleForm() date2 = '' if form.is_valid(): date2 = form.cleaned_data.get("my_date_field") # write date choosen by user to variable # And now I have a problem. I want to use the value of this variable to specify an endpoint: response = requests.get(f"http://api.nbp.pl/api/exchangerates/tables/a/2012-01-01/{date2}/") Api = response.json() context= {'form': form, 'submitbutton': submitbutton, "Api": Api} return render(request, … -
How to handle changing boolean field from database by ajax?
There is a piece of my html: <form action="" method="post"> {% csrf_token %} {% if donate.is_taken == False %} <br> <button type="submit" class="btn" name="taken_or_not" value="not_taken">Mark as taken</button> {% else %} <button type="submit" class="btn" name="taken_or_not" value="taken">Mark as not taken</button {% endif %} </form> There is a model: class Donation(models.Model): ... ... is_taken = models.BooleanField(default=False) How to create a ajax request, that the user is able to change the value 'taken_or_not' by a single button? Without any redirects, server loading etc. I am struggling to get it. Thanks for help. -
Django 3.0 django.core.exceptions.ImproperlyConfigured: Empty static prefix not permitted and user profile Upload
I am a newbie to Django development and developing an app where users can upload their details and profile picture. an error occurred. I have seen solutions but unable to solve it and also help me how to store uploaded profile picture into the disk. Kindly help me out. Here is my urls.py file from django.urls import path from django.conf import settings from django.conf.urls.static import static from django.views.generic.base import RedirectView from django.contrib.staticfiles.storage import staticfiles_storage from . import views urlpatterns = [ path('',views.home,name='home'), path('signup/',views.register,name='signup'), path('signup/register',views.register,name='signup'), path('signin/',views.signin,name='signin'), path('signin/signin',views.signin,name='signin'), path('logout/',views.logout,name='logout'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Here is my settings.py """ Django settings for AI project. Generated by 'django-admin startproject' using Django 3.0.7. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '4+aq#j(k%zq%(b%)o2&ln=2ex7-dykjo-(=hk1m3dxj2#&dtz_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS … -
django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
I had created a django application and using mysql as db back-end. Everything was working fine on my local machine so i tried to dockerize this application. And i have written code mentioned below to dockerize my application. docker-compose.yml version: '3' services: mysql: image: mysql:latest command: --default-authentication-plugin=mysql_native_password ports: - '3306:3306' environment: MYSQL_DATABASE: 'cool_db' MYSQL_ROOT_PASSWORD: 'hello@123*' container_name: mysql01 restart: always web: build: . container_name: django01 command: bash -c "python3 manage.py makemigrations && python3 manage.py migrate && python3 manage.py collectstatic --noinput && python3 manage.py runserver 0.0.0.0:8000" volumes: - my-vol:/src ports: - "8000:8000" links: - mysql depends_on: - mysql expose: - "8000" restart: always volumes: my-vol: Dockerfile FROM python:latest ENV PYTHONUNBUFFERED 1 RUN mkdir /src WORKDIR /src/ COPY ./requirements.txt /src/requirements.txt RUN pip install -r /src/requirements.txt COPY . /src/ EXPOSE 8000 requirements.txt autopep8==1.5.2 boto3==1.14.7 celery==3.1.24 channels==2.4.0 channels-redis==2.4.2 configparser==5.0.0 django==3.0.3 djangorestframework==3.11.0 mysqlclient==1.4.6 pre-commit==2.2.0 redis==2.10.6 requests==2.23.0 WhiteNoise==5.1.0 settings.py DATABASES = { "default": { "ENGINE": config.get("database", "DATABASE_ENGINE"), "NAME": config.get("database", "DATABASE_NAME"), "USER": config.get("database", "DATABASE_USER"), "PASSWORD": config.get("database", "DATABASE_PASSWORD"), "HOST": config.get("database", "DATABASE_HOST"), "PORT": config.get("database", "DATABASE_PORT"), } } config.cfg [database] DATABASE_USER: root DATABASE_PASSWORD: hello@123 DATABASE_HOST: mysql DATABASE_PORT: 3306 DATABASE_ENGINE: django.db.backends.mysql DATABASE_NAME: cool_db But when i run this code using sudo docker-compose up then my django service unable to connect with mysql … -
Why Java Script fetch web api is not giving the expected output?
when I am making ajax call in Django using J Query ajax it's logging the response but when I am using fetch it's not fetching anything. Why ? fetch("{% url 'mentor' %}", { method: 'GET', headers: { 'Content-Type': 'application/json' } }).then((res) => { console.log(res.data) }) $.ajax({ url: "{% url 'mentor' %}", method : 'GET', dataType: 'json', success: function (data) { mentors = data; console.log("mentor" , mentors) } }) Output undefined // fetch mentor (5) [{…}, {…}, {…}, {…}, {…}] //JQuery ajax -
I am getting error on sending email with celery 'send' object has no attribute '__qualname__'
here is my code i am sending email after registeration using celery but i am getting error like 'send' object has no attribute 'qualname' Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 2.2 Exception Type: AttributeError Exception Value: 'send' object has no attribute 'qualname' Exception Location: D:\DjangoPros\env\lib\site-packages\celery\local.py in getattr, line 143 Python Executable: D:\DjangoPros\env\Scripts\python.exe Python Version: 3.6.8 Python Path: ['D:\DjangoPros\Blog', 'D:\DjangoPros\env\Scripts\python36.zip', 'c:\users\sudheer\appdata\local\programs\python\python36\DLLs', 'c:\users\sudheer\appdata\local\programs\python\python36\lib', 'c:\users\sudheer\appdata\local\programs\python\python36', 'D:\DjangoPros\env', 'D:\DjangoPros\env\lib\site-packages', 'D:\DjangoPros\Blog', '.'] Server time: Wed, 29 Jul 2020 07:45:05 +0000 @shared_task def send(user_name=None,to_email=None): try: sleep(1) username="user_name" html_message = loader.render_to_string( 'security\mail_response.html', { 'user_name': username, }) subject="Hospectile Registration" message="Hello "+user_name+ 'You have registered sucessfully' from_email='smreddy475@gmail.com' to_list=(to_email,) send_mail(subject, message, from_email, to_list, fail_silently=True, html_message=html_message) except SMTPException as e: return e @unauthenticated_user def sign_up(request): if request.user.is_authenticated: return redirect('home_page') else: if request.method=='POST': try: print("Post data", request.POST) first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') username = request.POST.get('username') address = request.POST.get('address') password = request.POST.get('password') mobile = request.POST.get('mobile') user = User.objects.create_user(first_name=first_name, last_name=last_name,email=email, username=username, password=password) user.profile.address = address user.profile.email = email user.profile.mobile = mobile user.profile.active = True user.is_staff = True user.save() send.delay(user_name=username,to_email=email) messages.info(request, "You have registred successfully!") return redirect('login') except Exception as e:l̥ return HttpResponse(e) return render(request,'security/register.html') -
django nginx configuration run two project on different domain on same server
I want to run two domain on same server and same service in different folder. bellow are the nginx conf file I am trying to run request-micro service on same server with different domain and different folder. I am already running two test server domain on 2732 port in "home/user/test/" folder and its running fine, Now I am trying to run dev server on 2742 port in different directory "/home/user/dev/" but the test server request are coming on dev server. how can I differentiate dev and test server server { server_name test.domain1.co ; listen 80; location /request-micro { allow all; proxy_pass http://127.0.0.1:2732; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_cache_bypass $http_upgrade; client_max_body_size 2000M; alias /home/ubuntu/test/project/project; } } server { server_name test.domain2.co ; listen 80; location /request-micro { allow all; proxy_pass http://127.0.0.1:2732; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_cache_bypass $http_upgrade; client_max_body_size 2000M; alias /home/ubuntu/test/project/project; } } server { server_name dev.domain1.co ; location /request-micro { allow all; proxy_pass http://127.0.0.1:2742; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_cache_bypass $http_upgrade; client_max_body_size 2000M; alias … -
How to display product multiple images in Slider in Django?
I have a product model and this product model is related to images, it means that a product can have multiple images, but when i am displaying product it's images are not displaying. Please let me know how i can display product images in slider. here is my models.py file... class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) class ProductImage(models.Model): product=models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) image=models.ImageField(upload_to='product_image',blank=False,null=True) def save(self, *args, **kwargs): if not self.id: self.image = self.compressImage(self.image) super(ProductImage, self).save(*args, **kwargs) def compressImage(self, image): imageTemproary = Image.open(image) if imageTemproary.mode in ("RGBA", "P"): imageTemproary = imageTemproary.convert("RGBA") outputIoStream = BytesIO() imageTemproaryResized = imageTemproary.resize((1000, 700)) imageTemproaryResized.save(outputIoStream, format='JPEG', quality=20) outputIoStream.seek(0) image = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None) return image here is my views.py file... def productview(request, slug): product = Product.objects.get(slug=slug) template_name='mainpage/product-view.html' context={'product':product} return render(request, template_name, context) here is my product-view.html file for display single product... <div class="col-lg-6"> <div class="product-slick"> <div> <img src="{{product.first_image.image.url}}" alt="" class="img-fluid blur-up lazyload image_zoom_cls-0"> </div> </div> <div class="row"> <div class="col-12 p-0"> <div class="slider-nav"> <div> {% for img in product.image_set.all %} <img src="{{img.image.url}}" alt="" class="img-fluid blur-up lazyload"> {% endfor %} </div> </div> </div> </div> </div>