Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Filter object and create for million of records
get_or_create() is just a convenience function, but if i need to have (Filter+create) million of record in a single go?. bulk_create only create objects but not filtering. Can i do it using with transition or rawquery is the only solution? result = Model.objects.filter(field__lookup=value)[0] if not result: result = Model.objects.create(...) return result -
Web Application preferably in Django or Laravel with fingerprint detection
i got a project for school that asked me this stuff: It is a simple web application for fingerprinting users or visitors. Something similar as this one, except that we don't need to check if fingerprint is unique. https://amiunique.org/fp So the app should be modern and should respond to the visitor details of his device (OS, browser, IP address, country, city - this can be done via API /maxmind/... and some other information from device) Here you can use any framework as you want bootstrap or anything else... Design should be simple - in front page should have one button in the middle which says: Scan me or whatever, after clicking all results should appear on the page in organized way. Here is one example of front page: https://fingerprintjs.com/open-source/ The purpose of app is to detect if OS is outdated or browser is not latest version to inform user in some sort of windows. But that we can discuses later. Can you provide me some sources on how can i start this fingerprint thing, i have good knowledge of web developing html css js back-end and front-end, but implementing fingerprint is first time in my life. THANKS!!!! -
Django Model details displayed in the Bootstrap modal
Not sure if this question was asked before, but even that it is, it's out-dated, so pardon my repetition. I'll jump straight to it - I have a datable which is rendered from a complicated cross tabbed query, and it returns like 10 000+ rows, and in the very table I have a "detail" button which triggers a bootstrap modal, and when it opens it just shows some more unique details about the current object, or row. Now, the problem is, when the page where the table is, gets called, it takes so much time to load, it has 20 megabytes, which is a lot, and it takes like 5 seconds depending on the processor because every object gets loaded with his own modal (its happening inside the for loop). My question is, what is the best approach to load the details(bootstrap modal) only when the "details" button gets pressed. I tried something with Ajax, which was confused for me, so I would appreciate every suggestion. Thank you! This is the html of a table : % block content_row %} {% include 'partials/_alerts.html' %} <div class="card-body container-fluid"> {% include 'opportunity/opp_breadcrumb.html' %} <h2 class="-heading" style="margin-left: 50%">OPTIKA</h2> <table class="table table-bordered table table-hover … -
ModuleNotFoundError: No module named 'apidjangowithjwt.emailservice'
Folder Structure of my project where apidjangowithjwt is the project name & emailservice and user are the apps. views.py in user app where I am importing emailservice app which is giving the error Detailed error: File "F:\DjangoDemo\JWTAuthentication\apidjangowithjwt\user\views.py", line 17, in from apidjangowithjwt.emailservice.views import send_email ModuleNotFoundError: No module named 'apidjangowithjwt.emailservice' from apidjangowithjwt.emailservice.views import send_email **#giving error** views.py in emailservice app where I defined a function send_mail. from django.core import mail def send_email(**kwargs): with mail.get_connection() as connection: email=mail.EmailMessage(kwargs['subject'],kwargs['body'],kwargs['from_email'],kwargs['to_email'],kwargs['bcc'], connection,kwargs['attachments'],kwargs['header'],kwargs['bcc'],kwargs['reply_to']) email.send() I have also registerd my both apps in settings.py as: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'user', 'rest_framework', 'emailservice' ] -
FDB connection on Python closes itself
I am using FireBird connector for Python in my django app. I have a single connection per session, in order to minimize the loading times and increase the efficiency, but whenever the connection is being alive for more than 10 minutes, the connection "closes" itself. It's quoted because it doesn't really close itself, the object connection is still alive and the attribute closed of the class is set to False. In this state, whenever you try to execute a query, and fdb.fbcore.DatabaseError is thrown. This is my connector class I use to create a connection: class DBConnector(object): def __init__(self): print("Init Connector") self.host = 'the_host' self.database = 'the_database' self.user = 'the_user' self.password = 'the_super_secret_and_secure_key' self.charset = 'the_most_common_charset' self.dbconn = None def create_connection(self): print("Creating Connection") connection = fdb.connect( host=self.host, database=self.database, user=self.user, password=self.password, charset=self.charset, ) return connection def __enter__(self): self.dbconn = self.create_connection() return self.dbconn def __exit__(self, exc_type, exc_val, exc_tb): self.dbconn.close() When I do con = DBConnector() cursor = con.cursor() cursor.execute(MY_SELECT) It works perfect. Now if i let the connection alive for more than 10 minutes and try again to execute a query: cursor.execute(ANOTHER_SELECT) It throws fdb.fbcore.DatabaseError: Error while preparing SQL statement:\n- SQLCODE: -902\n- Unable to complete network request to host .\n- Error writing … -
DJANGO project admin page not opening
I was making a to do website using Django. And i encountered a weird error. As soon i start my server and type /admin to the url my server gets close. Not able to access the admin page. Any fixes? thanks. PS: my url file doesn't have any error. Image of the terminal : terminal screnshot -
Travis CI failing flake8 tests despite flake8 tests passing on local development environment?
Background I am building a project using Django, Docker, Travis CI and Flake8. My flake8 file: [flake8] max-line-length = 119 exclude = migrations, __pycache__, manage.py, settings.py, env When I run local flake8 tests using: docker-compose exec app python manage.py test && flake8 I receive an ok message with no error messages. My code is good! The problem When I push my code to master which automatically starts Travis CI, the Travis build fails due to the following errors: ./project/settings.py:94:80: E501 line too long (91 > 79 characters) ./project/settings.py:97:80: E501 line too long (81 > 79 characters) ./project/settings.py:100:80: E501 line too long (82 > 79 characters) ./project/settings.py:103:80: E501 line too long (83 > 79 characters) ./core/models.py:7:80: E501 line too long (93 > 79 characters) ./core/models.py:13:80: E501 line too long (104 > 79 characters) ./core/migrations/0001_initial.py:18:80: E501 line too long (126 > 79 characters) The command "docker-compose run app sh -c "python manage.py test && flake8"" exited with 1. My flake8 file specifically states that the max line length is 119 so these errors should not be happening (like they are not when running the test on my local machine). Does anyone know whats going on? -
How do i add a form to blog post detail?
So I Have a small django blog project. i have successfully built a blog post views and a blog post detail view. but i want to add a small form in the post detail page; so whenever you add a new post, a new form would be made in the detail page.i know how to make forms in general. please help me with the code -
websockets using django channels and angular 2+
I'm trying to create a simple create, retrieve, update, delete using django channels and have angular 2+ as my fronted. I'm unsure if I am on the right path but here is what I have so far. Below is my django consumers code: consumers.py class CourseConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'couses' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) code = text_data_json['courseCode'] name = text_data_json['courseName'] description = text_data_json['courseDescription'] created_by = text_data_json['course_created_by'] professor = text_data_json['course_professor'] course = models.Course.objects.get(pk=id) course.code = code course.name = name course.description = description course.created_by = created_by course.professor = professor async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'add_course', 'id': id, 'course': title, 'name': name, 'professor': professor, 'description': description, 'created_by': created_by } ) def add_course(self, event): code = event['courseCode'] name = event['courseName'] description = event['courseDescription'] created_by = event['course_created_by'] professor = event['course_professor'] self.send(text_data=json.dumps({ 'id': id, 'course': title, 'name': name, 'professor': professor, 'description': description, 'created_by': created_by })) routing.py from django.urls import path from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from course.consumers import CourseConsumer application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter([ path('courses/', CourseConsumer), ]) ), }) Below is my angular code: course.service.ts webSocket: WebSocketSubject<any>; messages: Observable<any>; connect(): void … -
nginx fails while the website somehow still works
Description I have built my Django3, gunicorn, nginx, Ubuntu 18.04, Digital Ocean project based on this guide. I only had 1 problem that it does not shows the CSS and all other static files like images. Before during the whole guide nginx have given the correct answers as the guide says and also currently the html site still online and running To solve this I was in the process of using this another guide to make my static files displayed on my site. I have done all the steps what the creator recommended but at the What I have tried After each step of the following [1.2.3...] commands I have executed the following commands to refresh: python3 manage.py collectstatic sudo nginx -t && sudo systemctl restart nginx sudo systemctl restart gunicorn 1.RUN: sudo ln -s /etc/nginx/sites-available/ch-project /etc/nginx/sites-enabled 1.RESULT: ln: failed to create symbolic link '/etc/nginx/sites-enabled/ch-project': File exists 2.RUN: /etc/nginx/sites-enabled/my-project 2.RESULT: -bash: /etc/nginx/sites-enabled/my-project: Permission denied 3.RUN: systemctl status nginx.service 3.RESULT: ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2020-03-26 13:27:08 UTC; 13s ago Docs: man:nginx(8) Process: 11111 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile … -
Is there a way to combine view functions of similar structures into one? Django
I'm a beginner at Django. Recently, I started writing a web app for inventory management and I realised that when i was writing the views, there were a lot of them with similar structures. For instance: def invoices(request): """The page for displaying invoices.""" invoice_list = Document.objects.filter(type_name__name='Invoice') page = request.GET.get('page', 1) paginator = Paginator(invoice_list, 10) try: invoices = paginator.page(page) except PageNotAnInteger: invoices = paginator.page(1) except EmptyPage: invoices = paginator.page(paginator.num_pages) context = {'invoices':invoices} return render(request, 'imsapp/invoices.html', context) and this one: def credit_notes(request): """The page for displaying credit notes.""" credit_notes_list = Document.objects.filter(type_name__name='Credit Note') page = request.GET.get('page', 1) paginator = Paginator(credit_notes_list, 10) try: credit_notes = paginator.page(page) except PageNotAnInteger: credit_notes = paginator.page(1) except EmptyPage: credit_notes = paginator.page(paginator.num_pages) context = {'credit_notes':credit_notes} return render(request, 'imsapp/credit_notes.html', context) So, I'm just thinking if there is a more elegant way to represent the above functions. Is class based view what I'm looking for? -
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f197e469a60>
hi guys i'm working in project with cms called tendenci which required to work with PostgreSQL and python django, I've been working on it on a virtual machine with Ubuntu and when i tried to migrate to production server (with Ubuntu also) i faced a lot of issues the last is migrate the db, actually i did all the required steps but it still showing an error when i try to run the server this is the command that i run python manage.py runserver this is the error that i get Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fadbc707a60> Traceback (most recent call last): File "/srv/mysite/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "site_settings_setting" does not exist LINE 1: SELECT (1) AS "a" FROM "site_settings_setting" WHERE ("site_... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/srv/mysite/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/srv/mysite/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/srv/mysite/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/srv/mysite/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/srv/mysite/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/srv/mysite/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/srv/mysite/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in … -
Template Not Found Error in Django while inlcuding html comments
Django version 2.0.7, Python3.6 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1>My Own Website via base file</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <!-- {% include 'navbar.html' %} --> {% block content %} {% endblock %} </body> </html> The above code throws an error, whereas the following one doesn't. The only difference is in the content of comment. Could someone explain ? I am using this code template to learn Django and this example of inheritance in templates throws TemplateDoesNotExist at /home/ error. <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1>My Own Website via base file</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in … -
Django custom permissions unable to call in decorator as i passed in params
I want to apply django permissions on viewsets and I create a decorator for this but its not working. I just want to call the permission class in decorator as passed in argument. views.py ''' class MapViewSet(viewsets.ModelViewSet): serializer_class = MapSerializer @permission_decorator(permission_class=MapPermission) def get_queryset(self): return Map.objects.all() ''' utils.py ''' METHODS = {'GET': 'view_permission', 'PATCH': 'add_permission', 'POST': 'add_permission', 'PUT': 'add_permission', 'DELETE': 'delete_permission'} def check_user_permission(permission, user, tag): # logic here return True/False class CustomBasePermissions(permissions.BasePermission): @abstractmethod def has_permission(self, request, view): pass class PermissionError(APIException): status_code = status.HTTP_403_FORBIDDEN default_detail = {'message': "You Don't have required permission"} class MapPermission(CustomBasePermissions): def has_permission(self, request, view): if request.role == "owner": return True else: permission = METHODS.get(request.method) return check_user_permission(permission, request.user, 'map') ''' decorators.py ''' def permission_decorator(permission_class): assert permission_class is not None, ( "@permission_decorator() missing required argument: 'permission_class'" ) def decorator(func): func.permission_classes = permission_class return func return decorator ''' -
Python - Covert enum to Django models.CharField choices tuple
I have this enum: class Animal(Enum): DOG = 'dog' CAT = 'cat' and in a Django model I have this: possible_animals = ( ("DOG", "dog"), ("cat", "cat"), ) animal = models.CharField(choices=possible_animals, ...) I know I can use the enum like this: possible_animals = ( (Animal.DOG.name, Animal.DOG.value), (Animal.CAT.name, Animal.CAT.value), ) but is there any other elegant dynamic way to convert the enum into this kind of nested tuple? -
Make Post in django
How can you allow users to post something on the website using Django framework? My views.py file : from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.utils import timezone from . import models from django.contrib.auth.models import User @login_required def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['url']: post = models.Post() post.title post.url post.pub_date post.author post.save() return redirect('create') else: return render(request, 'posts/create.html') my models.py : from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) url = models.TextField() pub_date = models.DateTimeField() author = models.ForeignKey(User, on_delete=models.CASCADE,default=1) votes_total = models.IntegerField(default=1) and my create.html file: <h1> Create Post</h1> {% if error%} {{ error }} {% endif%} <br /> <br /> <br /> <form method='POST' action="{% url 'create' %}"> {% csrf_token %} Title: <input type="text" name="title"> <br /> <br /> URL: <br /> <input type="text" name="url"> <br> <br> <input type="submit" value="Post"> </form> The problem is the post doesn't even show up in the admin panel and i also get this error NameError at /posts/create/ name 'post' is not defined thank you -
Django - Create a table/model from two models
I have two models in Django; Model 1 has information and an ID Model 2 has specific more information about the ID in Model 1 Does anyone know how I could create another model, view and template (or the process) that takes the information from model 1 based on its ID and then links/binds it with the other detailed information for that ID from Model 2 creating another model/db for a detailed table/view of the combined models? I have searched extensively but nothing is to clear and I am still learning but getting there slowly. Thank you all and I hope your all safe. -
Django Signals - How to save the instance
I am using Django Rest Framework to upload videos. Now I wanted to add thumbnails to my video files. Whenever a Video object is saved, I wanted to create a thumbnail and set its thumbnail field. My Video model looks like this: class Video(models.Model): created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=100, blank=True) video = models.FileField(upload_to='Videos/',blank=True) thumbnail = models.ImageField(upload_to = 'Images/', blank = True) My signal handler looks like this: from moviepy.video.io.VideoFileClip import VideoFileClip from posts.models import Video from django.db.models.signals import post_save from django.dispatch import receiver from settingsFolderOfProject.settings import MEDIA_ROOT import os # when save() of Video is done, create_thumbnail_from_video() is called @receiver(post_save, sender=Video) def create_thumbnail_from_video(sender, instance, created, **kwargs): if created: # create the clip using moviepy's VideoFileClip class clip = VideoFileClip(os.path.join(MEDIA_ROOT, instance.video.name)) # create the frame at 1st second and set it to instance's thumbnail field instance.thumbnail = clip.save_frame(os.path.join(MEDIA_ROOT, 'Images/thumbnail.jpg'),t='00:00:01') # save the instance instance.save() # <--- I think this op does not work properly What I have to change? The thumbnail file gets created in the folder as expected but Django does not set the thumbnail field of my Video model instance. The thumbnail field of the created Video instance is still set to null. -
Django docker-compose cannot see MySQL database
I'm new to docker. I am trying to get docker-compose to initiate a MySQL database and then use a Django project to connect to that database. The Dockerfiles that I am using is: FROM python:3.6 RUN mkdir /code WORKDIR /code COPY ./ /code/ RUN pip install -r requirements.txt I then use the following to make that Dockerfiles into an image: docker build -f ./docker/dockerfile -t mark/markswebsite . I have the following within Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbMarksWebsite', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'mydb', 'PORT': '3306', }} The docker-compose.yml file is: version: '3' services: mydb: image: mysql:5.7 environment: MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: dbMarksWebsite web: environment: - DJANGO_DEBUG=1 - DOCKER_DB_HOST=mydb image: mark/markswebsite stdin_open: true tty: true command: python manage.py collectstatic --noinput command: python manage.py makemigrations ports: - "8080:8080" depends_on: - mydb I WOULD LIKE TO ADD THE FOLLOWING, BUT AT PRESENT IT FAILS ON make migrations: python manage.py migrate python manage.py runserver And I am using the following to initiate it: docker-compose -f ./docker/docker-compose.yml up -d I have had a number of problems with this, but when I connect to the logs of the website, currently I am getting this error message: ....... jango.db.utils.OperationalError: (2002, "Can't connect to … -
method to serialize comment(model) datas using parent field to get comment's reply in Django
I have made FoodComment model like this in Django using Foreignkey. It uses username to specify user who owns the comment, and food is for menu which to collect comments of users. And parent points other FoodComment object if it is comment's reply. class FoodComment(models.Model): username = models.ForeignKey(Account, on_delete=models.CASCADE) food = models.ForeignKey(Food, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) body = models.CharField(max_length=30) star = models.IntegerField(default=5) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.food.menuname + ':' + self.username.username I am having problem with serializer getting jsoned comments data with hierarchy of comments and that of replies. class FoodCommentList(APIView): serializer_class = CommentSerializer def get(self, request, foodname): food = Food.objects.get(menuname=foodname) data = FoodComment.objects.select_related('food').filter(food=food, parent=None) serialized = CommentSerializer(data, many=True) return Response(serialized.data, HTTP_200_OK) If i use views.py's FoodCommentList function as above, REST returns serialized.data as below. [{"id":1,"body":"delicious!","star":5,"created":"2020-03-26T20:56:49.111307","username":2,"food":19,"parent":null}] And CommentSerializer used above looks like this. class CommentSerializer(serializers.ModelSerializer): class Meta: model = FoodComment fields = '__all__' What I am trying to do is not just serialize 'parent=None' data but with parent field, I want to get json data with comment's reply like this using serializer. { id:1, body:"delicious!", ... childs: { id:2, body:"ty!", ... } ] I have tried code by other users but couldn't solve it. Is … -
Why are my products not getting added to the cart?
I'm trying to develop a django s=online store website. when clicking on add to cart, the products are not being displayed on the cart. Can anyone please help me out? my views.py: from django.shortcuts import render, redirect, HttpResponseRedirect from products.models import Product from .models import Cart from django.contrib import messages from django.urls import reverse def cart(request): cart = Cart.objects.all()[0] context = {"cart":cart} template = 'shopping_cart/cart.html' return render(request, template, context) def add_to_cart(request): cart = Cart.objects.all()[0] if not Product in cart.Products.all(): cart.products.add(Product) else: cart.products.remove(Product) return HttpResponseRedirect(reverse('cart')) my models.py: from __future__ import unicode_literals from django.db import models from products.models import Product class Cart(models.Model): products = models.ManyToManyField(Product, null=True, blank=True) total = models.DecimalField(max_digits=100, decimal_places=2, default = 0.00) def __unicode__(self): return "Cart" my urls.py: from django.contrib import admin from django.urls import path, include from products import views from shopping_cart import views as sc_views urlpatterns = [ path('admin/', admin.site.urls), path('cart/', sc_views.cart, name='cart'), path('cart/', sc_views.add_to_cart, name='add_to_cart'), path('', include('products.urls')) ] -
Django return distinct images
I have a 3 x 3 grid and I am trying to return randomly selected images that are distinct from a given directory. I am currently getting images as an output but some of them are repeated. There are a total of 10 images in the directory, all numerically named. Screenshot of Current output: Output What should I do to get distinct images as my output? P.S: I am new to Django so any any help would be greatly appreciated. random_Image.py - Template tag returning a list of selected images @register.simple_tag def random_image(image_dir): valid_extensions = ['.jpg', '.jpeg', '.png', '.gif'] rand_dir = '/static/app_pickfeel/images/' # print(rand_dir) files = [f for f in os.listdir(settings.BASE_DIR + '/app_pickfeel/static/app_pickfeel/images') if f[f.rfind("."):len(f)] in valid_extensions] remove_duplicate = set(files) final_list = list(remove_duplicate) return rand_dir + random.choice(final_list) random_Image.py: Output for 'files' {'2.gif', '5.jpg', '6.jpg', '1.jpg', '9.jpg', '8.jpg', '4.jpg', '7.jpeg', '3.jpg'} {'2.gif', '5.jpg', '6.jpg', '1.jpg', '9.jpg', '8.jpg', '4.jpg', '7.jpeg', '3.jpg'} {'2.gif', '5.jpg', '6.jpg', '1.jpg', '9.jpg', '8.jpg', '4.jpg', '7.jpeg', '3.jpg'} {'2.gif', '5.jpg', '6.jpg', '1.jpg', '9.jpg', '8.jpg', '4.jpg', '7.jpeg', '3.jpg'} {'2.gif', '5.jpg', '6.jpg', '1.jpg', '9.jpg', '8.jpg', '4.jpg', '7.jpeg', '3.jpg'} {'2.gif', '5.jpg', '6.jpg', '1.jpg', '9.jpg', '8.jpg', '4.jpg', '7.jpeg', '3.jpg'} {'2.gif', '5.jpg', '6.jpg', '1.jpg', '9.jpg', '8.jpg', '4.jpg', '7.jpeg', '3.jpg'} {'2.gif', '5.jpg', '6.jpg', '1.jpg', '9.jpg', '8.jpg', … -
How to retrieve image url saved into models in views
I want to fetch image URL which is successfully getting stored in database using models.py Now I want to fetch url or location of image in a string variable in views.py My models.py class Document(models.Model): document_id = models.AutoField document_name = models.CharField(max_length=50, null=False, blank=False, default="") document_img = models.ImageField(upload_to='media', default="", blank=False, null=False) document_desc = models.CharField(max_length=500, default="", blank=False, null=False) document_date = models.DateField() here is views.py def upload(request): if request.method == 'POST' and request.FILES['doc_img']: document = Document() document.document_name = request.POST.get('doc_name') document.document_img = request.FILES['doc_img'] document.document_desc = request.POST.get('doc_desc') document.document_date = request.POST.get('doc_date') document.save() doc = Document.objects.all() img_path = doc[0].document_img return HttpResponse(img_path) else: return HttpResponse('Failed To Upload') I know we can show image in html template by <img src='{{doc.0.document_img}}'> but i want it in a python variable Can anyone Help me -
Dango getting error while running manage.py runserver
I want to run my django API to my IP address which is 192.168.1.5:81 with port number but i am getting that You don't have permission to access that port. I have done port forwarding in my router. i am doing this because i want to get data in my android application using retrofit. enter image description here -
How can I disable URL redirect when I have a "next" url? - Django
I have created a blog with Django and whenever a user logs in, the URL redirects to the homepage and displays a success message. This is fine, however, whenever a login is required to view a certain page, Django redirects to the login page and attaches "?next=" to the end of the URL to redirect back to the previous page. The problem is that after the user logs in, the "next" URL is not executed and Django redirects to the homepage and displays the success message? Is there a way to disable this redirect whenever there is a "next" URL? views.py from django.urls import reverse from django.contrib import messages from django.shortcuts import render, redirect from django.contrib.auth import login from django.utils.safestring import mark_safe from .forms import UserLoginForm def login_view(request): if request.method == 'POST': form = UserLoginForm(data=request.POST) if form.is_valid(): student = form.get_user() login(request, user) create_url = reverse('post-create') messages.success(request, mark_safe(f'You are now logged in. Do you want to <a href="{ create_url }" class="link" title="Create a post">create a post</a>?')) return redirect('home') else: form = UserLoginForm() return render(request, 'users/login.html', {'form': form, 'title': 'Log in'})