Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
Django-templated-email not connecting to my template file
I am sure that i have set up everything correctly and my template file welcome.email is in right folder but somehow when sending email, it is not showing as my template has been connected. Here is my view for django-template-email: def send(request, pk): if request.method == "POST": data = json.loads(request.body) trainingtitle = data['trainingtitle'] name = data['name'] email = data['email'] send_templated_mail( template_name='welcome', from_email='austin.roose1@gmail.com', recipient_list=['austin.roose1@gmail.com'], context={ 'email': email, 'name': name, 'trainingtitle': trainingtitle, }, ) return redirect('/api/') And i have also in my settings.py file: TEMPLATES = [ { 'DIRS': [os.path.join(BASE_DIR, 'templates')], My welcome.email file looks like: {% block html %} <p>Hi {{name}},</p> <p>You just signed up for my website, using: <dl> <dt>username</dt><dd>{{name}}</dd> <dt>join date</dt><dd>{{email}}</dd> </dl> </p> <p>Thanks, you rock!</p> {% endblock %} But my sent email looks like: As you can see it shows 'username' and 'full name' in there although i don't have them in my template. What should i change? -
Can't create DB on Heroku
I have deployed my Django app on Heroku, in Heroku bash I ran python manage.py migrate, but it still returns error Exception Value:no such table: project_sliderimage. Also checked if db was created with heroku addons and db state is created. -
Starting python django server, with task Schedular
I have a django project, which i want to always start when ever the computer starts. I have created a bach file to run surver, and open the project in a browser. When i click on it, it runs the server and opens the browser. But when i put in task schedular, it only opens the browser but doesn't run server. this is my batch file. @ECHO OFF start cmd.exe /C "python manage.py runserver && cd C:\myproject" start C:\"Program Files (x86)"\Google\Chrome\Application\chrome.exe "http://127.0.0.1:8000/" -
I want to add create bar with add button in Django
I am new to django and kind of confuse why it's not working I making list website where you add something on list and it updates shows the new added element on the same page. I am almost done the only thing left is creating new element where i am facing problem. Thank you models.py:- from django.db import models from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse # Create your models here. class simpleList(models.Model): title = models.CharField(max_length=250) def __str__(self): return self.title views.py:- from django.shortcuts import render, get_object_or_404 from .models import simpleList from django.views.generic import ListView, DeleteView, CreateView from django.urls import reverse_lazy from django.contrib.messages.views import SuccessMessageMixin # Create your views here. class ListListView(ListView): model = simpleList template_name = 'list_list.html' class DeleteList(SuccessMessageMixin, DeleteView): model = simpleList success_url = reverse_lazy('list_list') success_message = "deleted..." def delete(self, request, *args, **kwargs): self.object = self.get_object() title = self.object.title request.session['title'] = title return super(DeleteView, self).delete(request, *args, **kwargs) class CreateList(CreateView): model = simpleList template_name = 'list_list.html' urls.py:- from django.urls import path from .views import ListListView, DeleteList, CreateList from django.conf.urls import url from . import views urlpatterns = [ path('', ListListView.as_view(), name='list_list'), path('<int:pk>/delete/', DeleteList.as_view(), name='delete_view'), path('new/', CreateList.as_view(), name='create_list'), ] list_list.html:- {% extends 'base.html' %} {% block … -
Is it possible to inform Webpack that asset was used in Django template?
I have a project, I use both Django and Webpack for bundling and process assets. My goal is to make Webpack process all assets, e.g. optimize images. If image is used in js / css file there is no problem. Things are going complicated when I use img only in Django template. Is there a way to 'inform' Webpack, that particular img is used, and update path for it in django template after webpack process it ? -
@login_required decorators doesn't wok perfectly though signout is done,we can still go back to index page
Although using @login_required on index page, if Signout is done and redirect to login page, again we can visit the index page by clicking the back arrow in browser. Is there any mistake on code? views.py in expenses from django.contrib.auth.decorators import login_required @login_required(login_url='/authentication/login') def index(request): expenses = Expense.objects.filter(owner=request.user) urls.py from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path('register', RegistrationView.as_view() , name ="register"), path('login', LoginView.as_view(), name="login"), path('logout', LogoutView.as_view(), name="logout"), path('validate_username', csrf_exempt(UsernameValidationView.as_view()), name="validate_username"), path('validate_email', csrf_exempt(EmailValidationView.as_view()), name="validate_email") ] view.py in authentication class LogoutView(View): def post(self,request): logout(request) messages.warning(request, 'You have been Logout!!') return redirect('login') class LoginView(View): def get(self, request): return render(request, 'authentication/login.html')