Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In mpld3 how to make draggable line using mouse pointer?
I am trying to drag red vertical line in vertical direction towards right and left side using mouse pointer and on release I want to print x-axes value. I am not able to connect line_a with DragPlugin class. I followed https://mpld3.github.io/examples/drag_points.html this code as a reference. """ Draggable Points Example ======================== This example shows how a D3 plugin can be created to make plot elements draggable. A stopPropagation command is used to allow the drag behavior and pan/zoom behavior to work in tandem. """ import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import mpld3 from matplotlib import lines from mpld3 import plugins, utils class DragPlugin(plugins.PluginBase): JAVASCRIPT = r""" mpld3.register_plugin("drag", DragPlugin); DragPlugin.prototype = Object.create(mpld3.Plugin.prototype); DragPlugin.prototype.constructor = DragPlugin; DragPlugin.prototype.requiredProps = ["id"]; DragPlugin.prototype.defaultProps = {} function DragPlugin(fig, props){ mpld3.Plugin.call(this, fig, props); mpld3.insert_css("#" + fig.figid + " path.dragging", {"fill-opacity": "1.0 !important", "stroke-opacity": "1.0 !important"}); }; DragPlugin.prototype.draw = function(){ var obj = mpld3.get_element(this.props.id); var drag = d3.drag() .on("drag", dragged) obj.elements() .data(obj.offsets) .style("cursor", "default") .call(drag); function dragstarted(d) { d3.event.sourceEvent.stopPropagation(); d3.select(this).classed("dragging", true); } function dragged(d, i) { d[0] = obj.ax.x.invert(d3.event.x); d[1] = obj.ax.y.invert(d3.event.y); d3.select(this) .attr("transform", "translate(" + [d3.event.x,d3.event.y] + ")"); } function dragended(d) { d3.select(this).classed("dragging", false); } } """ def __init__(self, points): if … -
Select This button in HTML
I am building a BlogApp and I am working in a Image Cropping Feature AND i am stuck on a Problem. What i am trying to do :- There's a Image Cropping Feature in Create BlogPost page. AND when user fill all the details then user selects a image from Directory and crop it and THEN The Problem Is, There are two buttons in Image Cropping Section Back and Crop and Upload button. AND When user clicks on Back then it return to the Create Blog page without selected the image( which is good ) BUT when it click on Crop and Upload then blog is saving without return to Create Blog page and I want a button of Select this Image , So when user clicks on button then it will return in Create Post Section with the selected image. BUT i don't know how can i do it. What have i tried I have tried <input type="submit" value="okay" /> BUT it didn't work for me. I have also tried ` tag, BUT it also didn't work for me. create_post.html <div class="modal fade" id="modalCrop"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 … -
Django - print query result to html
I need some help with Django please. I am working on a questionnaire. I made a raw query where I made a summation with two cells of the same row. I can't find the method to print it to my HTML. views.py def query(request): my_query = Stressz_teszt.objects.raw('SELECT ID, stressz_v05 + stressz_v06 FROM stressz_stressz_teszt') context = { 'my_query': my_query, } return render(request, 'stressz/query.html', context) query.html {{ my_query }} {% for i in my_query %} {{ i.stressz_company }} --- {{ user }} --- {{ summation here !!! }} {% endfor %} Thank you for you reply in advance! -
Django admin error ValidationError: ['ManagementForm data is missing or has been tampered with'] due to conditional inline use
I have a custom User model(AbstractUser) and a Stock model. Assume there's multiple user roles manager, supplier etc. The manager can be able to view other manager's details and supplier details. The User model got a conditional inline which shows the stocks of each supplier if the user role is equalled to supplier.(Here role is a PositiveSmallIntegerField with choices and SUPPLIER = 2) class SupplierStockInline(admin.StackedInline): """ Inline to show stocks of a supplier """ model = Stock extra = 0 @admin.register(User) class UserAdmin(UserAdmin): """ User """ fieldsets = [ (None, {'fields': ('username', 'password')}), ('Personal info', {'fields': ( 'first_name', 'last_name', 'email', ... some custom fields... )}), ('Permissions', {'fields': ( 'is_active', 'is_staff', 'is_superuser', 'role', 'groups', 'user_permissions', )}), ('Important dates', {'fields': ('last_login', 'date_joined')}) ] list_display = [...] search_fields = [...] # --- the source of the problem --- inlines = [] def get_inlines(self, request, obj): """ Show inlines, stocks of supplier """ try: if obj.role == SUPPLIER: return [SupplierStockInline] except: pass return [] # --- ---- ----- This works just fine till I tried to change the role of a new user to supplier. ValidationError: ['ManagementForm data is missing or has been tampered with'] The issue is due to that overridden get_inlines() method. … -
Field 'id' expected a number but got 'Henry' (AJAX & DRF)
I am trying to get a user's list with an AJAX request and DRF. But get this error: Field 'id' expected a number but got 'Henry'. I'd be grateful for any assistance. AJAX: const showUserLists = function(map){ let userName = "Henry"; $.ajax({ type: 'GET', url: '/api/userlist/', data: { 'username': userName }, success: function (data) { data.forEach(item => { console.log(item.list_name) $("#userLists").append("<li class=userlist data-name=\"" + item.list_name + "\">" + item.list_name + "</li>") }) } }); }; urls.py: router = DefaultRouter() #need help understanding router register router.register('userlist', views.UserListViewSet, basename= 'userlist') views.py #this shows all lists for a user class UserListViewSet(viewsets.ModelViewSet): serializer_class = UserListSerializer def get_queryset(self): name = self.request.GET.get('username', None) return UserList.objects.filter(user=name) Serializer: class UserListSerializer(serializers.ModelSerializer): #this is what we worked on on October 1 class Meta: model = UserList fields = ['id', 'user', 'list_name'] class VenueListSerializer(serializers.ModelSerializer): created = serializers.ReadOnlyField() class Meta: model = VenueList fields = ['id', 'title'] Relevant model: class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) #is this okay? def __str__(self): return self.list_name Traceback Traceback (most recent call last): File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'Henry' The above exception was the direct cause of the following exception: Traceback (most recent call … -
Setting up React.js with Django failed
I am currently learning React.js and I followed some tutorial on Youtube for React.js basics. I didnt initially use npm run build(used it after im done coding frontend) and i created my react frontend app inside my django project. When I am running npm start on cmd, react app works perfectly fine on localhost:3000. enter image description here But after I tried to run npm run build and done setting up, STATICFILES_DIRS, template_dirs, STATIC_URL and such, when I runserver on port:8000 which is default for django, all I can see is a white screen, I included console on the screenshot for error references: empty django page with console I even tried to put some text inside the body 'frontend/build/index.html' just to see if django can access the template dirs, and the text put in shown on django homepage localhost:8000. -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/asa/ Raised by: products.views.ProductDetailSlugView Error
i've tried almost everything,can't figure out whats going on?! i think "try" logic is correct in ProductDetailSlugView, im using Django verson 2.2, in main url i have include, everything is working until SlugView and i have no idea whats happening :( i did researches almost everywhere, i tink im missing something i don't know products/views.py from django.http import Http404 from django.views.generic import ListView, DetailView from django.shortcuts import render, get_object_or_404 from .models import Product class ProductListView(ListView): template_name = "products/list.html" # def get_context_data(self, *args, **kwargs): # context = super(ProductListView, self).get_context_data(*args, **kwargs) # print(context) # return context def get_queryset(self, *args, **kwargs): request = self.request return Product.objects.all() def product_list_view(request): queryset = Product.objects.all() context = { 'object_list': queryset } return render(request, "products/list.html", context) class ProductDetailSlugView(DetailView): queryset = Product.objects.all() template_name = "products/detail.html" def get_context_data(self, *args, **kwargs): context = super(ProductDetailSlugView, self).get_context_data(*args, **kwargs) return context def get_object(self, *args, **kwargs): request = self.request slug = self.kwargs.get('slug') try: instance = Product.objects.get(slug=slug, active=True) except Product.DoesNotExist: raise Http404("Not found..") except Product.MultipleObjectsReturned: qs = Product.objects.filter(slug=slug, active=True) instance = qs.first() except: raise Http404("Error") return instance class ProductDetailView(DetailView): #queryset = Product.objects.all() template_name = "products/detail.html" def get_context_data(self, *args, **kwargs): context = super(ProductDetailView, self).get_context_data(*args, **kwargs) print(context) # context['abc'] = 123 return context def get_object(self, *args, **kwargs): request … -
Database not updating with custom save method
class Bike(models.Model): BikeFile = models.FileField(null=True, upload_to='') RegoNumber = models.CharField(max_length=10) RegoExpiry = models.DateField( auto_now=False, auto_now_add=False, null=True) LastRentedDate = models.DateField( auto_now=False, auto_now_add=False, editable=True, null=True) Hire = models.OneToOneField( Hire, on_delete=models.SET_NULL, null=True, related_name='Hire') def __str__(self): return self.RegoNumber def save(self, *args, **kwargs): if self.Hire != None: # Why isn't this running print(localdate()) self.LastRentedDate = localdate() print(f'{self.LastRentedDate} is last rented date from model') self.BikeFile = f'{self.RegoNumber}\'s hire on {self.Hire.StartRentDate}.pdf' return super(Bike, self).save(*args, **kwargs) For some reason self.LastRentedDate is not updating in the database, even though when I run the save on the Bike the print(f'{self.LastRentedDate} is last rented date from model') runs with the proper localdate(). Assignment to self.BikeFile also works -
How to add another model in ListView that has forign key with the main model
Sorry for my bad english I'm making a dashboard website I have 2 models the second one has foreign key of the first one example of josn model1: { id:1, name: name1, location: location1 } model2: { id:1 model1_id: 1 photo: "http://url/media/picures/myphoto478998691182.jpg" ... } So there supposed to be more of model2 to each model1 instance In my views I have a ListView of model1 I want to add to last photo of model2 referring to each model1 id If I have 2 instances of model1 each has 5 instances of model2 I want to filter model2 by id and get the last photo for each instance in model1 How to fix this code: class Model1List(CustomLoginRequired, ListView): model = Model1 paginate_by = 100 def get_context_data(self, **kwargs): photo_list = Model2.objects.filter(model1_id = self.kwargs.get('id')) photo = list(photo_list.values_list('photo', flat=True))[-1] context = super().get_context_data(**kwargs) context['now'] = timezone.now() context['photo'] = photo return context So I can use in the html template somehow like this {% for object in object_list %} <div class="branches-list-unit" id="{{ object.slug }}"> <h5 class="branch-list-unit__name">{{ object.name }}</h5> <img class="branch-list-unit__img" src="{{ object.photo }}" </div> {% endfor %} -
uWSGI Segmentation Fault Prevents Web Server Running
I am currently running a web server through two containers: NGINX Container: Serves HTTPS requests and redirects HTTP to HTTPS. HTTPS requests are passed through uwsgi to the django app. Django Container: Runs the necessary Django code. When running docker-compose up --build, everything compiles correctly until uWSGI raises a Segmentation Fault. .... django3_1 | Python main interpreter initialized at 0x7fd7bce0d190 django3_1 | python threads support enabled django3_1 | your server socket listen backlog is limited to 100 connections django3_1 | your mercy for graceful operations on workers is 60 seconds django3_1 | mapped 145840 bytes (142 KB) for 1 cores django3_1 | *** Operational MODE: single process *** django3_1 | !!! uWSGI process 7 got Segmentation Fault !!! test_django3_1 exited with code 1 Would appreciate if there's any advice, as I'm not able to see into the container for debugging purposes when it is starting up, therefore I don't know where this segmentation fault is occurring. The SSL certificates have been correctly set up. -
Cant install tflite_runtime while deploying on web application online
System information OS Platform and Distribution (windows 10) TensorFlow version: Uninstalled(As I cannot use such a huge library) Python version: 3.8 Installed using virtualenv and pip3 on local requirements.txt GPU 8Gb memory: I am new to this but I will try to explain my situation. So I am using tflite.interpreter to load the saved model(converted to tflite) using tflite. interpreter. Everything works fine on the local system but when I deploy my Django app to Heroku or azure. I cant install tflite_runtime from Requirements.py during git push to remote. I used this to install it on my local pip3 install --extra-index-url https://google-coral.github.io/py-repo/ tflite_runtime How do I include tflite_runtime in requirements.txt so that it automatically installs using pip while pushing to GIT? -
'unique_together' refers to the nonexistent field 'semantics_tmplt'
Django 3.1.7 class BranchSemanticsTemplate(models.Model): semantics_tmplt = models.ForeignKey(SemanticsLevel2Tmplt, on_delete=models.PROTECT, verbose_name=gettext("Semantics template"), related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ), branch_tmplt = models.ForeignKey(BranchTmplt, on_delete=models.PROTECT, verbose_name=gettext("Branch template"), related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ), class Meta: verbose_name = gettext("Branch template - branch- semantics - semantics template") verbose_name_plural = verbose_name unique_together = ['semantics_tmplt', 'branch_tmplt', ] Problem: (venv) michael@michael:~/PycharmProjects/ads6/ads6$ python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: dashboard.BranchSemanticsTemplate: (models.E012) 'unique_together' refers to the nonexistent field 'branch_tmplt'. dashboard.BranchSemanticsTemplate: (models.E012) 'unique_together' refers to the nonexistent field 'semantics_tmplt'. Could you help me here? -
AttributeError: x object has no attribute 'GET' (DRF)
I am trying to grab a user's list using Django Rest Framework and an Ajax request. However, I get the following error AttributeError: 'UserListViewSet' object has no attribute 'GET' Not sure what I am doing wrong - I am newer to DRF than vanilla Django. Ajax call: const showUserLists = function(map){ let userName = "Henry"; $.ajax({ type: 'GET', url: '/api/userlist/', data: { 'username': userName }, success: function (data) { data.forEach(item => { console.log(item.list_name) $("#userLists").append("<li class=userlist data-name=\"" + item.list_name + "\">" + item.list_name + "</li>") }) } }); }; urls.py: router = DefaultRouter() router.register('userlist', views.UserListViewSet, basename= 'userlist') router.register('uservenue', views.UserVenueViewSet, basename= 'uservenue') views.py #this shows all lists for a user class UserListViewSet(viewsets.ModelViewSet): serializer_class = UserListSerializer def get_queryset(request): name = request.GET.get('username', None) return UserList.objects.filter(user=name) Traceback: Traceback (most recent call last): File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, … -
Trouble rendering results from searchbar in Django
I have been working on a search bar in django and I am close but having some issues rendering the results to the page. Views.py class SearchResultsView(ListView): model = Project template_name = 'search_results.html' def get_queryset(self): proj=self.request.GET.get('proj') proj_list=Project.objects.filter( Q(name__icontains=proj) | Q(projectTag__icontains=proj) ) proj_list1=Project.objects.filter( Q(department__icontains=proj) ) proj_list2 = list(set(proj_list) & set(proj_list1)) return proj_list2 class SearchPageView(TemplateView): template_name = 'searchbar.html' search_results.html {% extends 'main/base.html' %} <html> {%block content%} <h1> Search Results </h1> {% if proj %} <ul> {% for project in proj_list2%} <li> {{project.name}}, {{project.department}}, {{project.projectTag}} </li> {% endfor %} </ul> {% else %} <h2>sorry, no results</h2> {% endif %} {%endblock%} </html> Whenever I search something that should definitely yield results, I get "sorry, no results." Thank you. Please help me to understand my disconnect. The bigger aim for this is to then add different models to query from (i.e. not just search in projects, but also search by user). -
Cross-origin API call from a node.js server to a django server, need to edit data on the django side
For a project I am using a really old version of django (1.5.2). An app has been created using this version of django long time ago, and I am making a separate app that needs to make API calls to the django app. My separate app is in node.js/typescript. From my node app, I need to be able to POST some data to the django app. I have created the new API inside the django app, and it works internally. If I try to call the endpoint from my node app, it does not work - the method is called, but the posting part does not work as it looks for authentication and since I sent the request from the node app, the user shows up as AnonymousUser, who is non-authenticated. For APIs that do not require POST (just GET), I can access the django API endpoints from node since I defined CORS MiddleWare in the django app. I was wondering how I might be able to POST information from node app to the django app, and also authenticate user if the user is logged into the django app from another tab. -
Авторизация в андроид приложении
Я недавно начал изучать разработку под андроид на kotlin. Пишу небольшое клиент-серверное приложение. Серверная часть на Django готова и работает. Теперь прикручиваю интерфейс. Есть несколько вопросов: Я уже умею сделать запрос с логином и паролем. В ответ, если всё хорошо, Django присылает куки, в которых есть SCRF токен, id сессии, время жизни токена и сессии. Как мне сохранять эти куки в приложении для последующего использования? При открытии приложения мне надо как-то понимать, авторизован ли пользователь. Как это правильно сделать? Думал просто проверять наличие сохраненных куки, если всё с ними ок, значит авторизован. если их нет или время жизни закончилось, то снова запрашивать логин и пароль. Но может есть более православный способ? Есть данные, которые требуется синхронизировать с удаленной БД (например, список городов). Как это лучше реализовать? SQLLite и при открытии приложения синхронизировать все необходимые данные? Или есть более православный способ? -
How can I get image from android app to Django
I want to get image from android app to Django server. How can I get image? I use Django REST-Framework. And I want to save image to server. What should I use?(filefield or imagefield) -
TemplateDoesNotExist at /trade/confirm/
When a user clicks a button in a form, I am sending a POST request in a form with action="{% url 'trade-confirm' %}". The method that is called, insert_transaction, is working correctly. But when that method is finished it returns a DetailView, TransactionDetailView, which is showing the below error: TemplateDoesNotExist at /trade/confirm/ confirmed-trade/20/ Screenshot of error here: enter image description here Below is my code: Folder structure: game-exchange -blog --migrations/ --static/ --templates/ ---blog/ ----about.html ----base.html ----matches.html ----transaction.html ----your-trades.html --admin.py --apps.py --models.py --urls.py --views.py -django_project/ -media/ -users/ -manage.py -posts.json -Procfile blog/urls.py urlpatterns = [ #the 2 relevant url's path('confirmed-trade/<int:pk>/', views.TransactionDetailView.as_view(), name='confirmed-trade'), # Loads transaction form path('trade/confirm/', views.insert_transaction, name='trade-confirm'), # url to accept POST call from Your Trades page to create a Transaction ] blog/models.py (transaction object only) class Transaction(models.Model): name = models.TextField() created_date = models.DateTimeField(default=timezone.now) trade_one = models.ForeignKey(Trade, on_delete=models.CASCADE, related_name='trade_one', db_column='trade_one') trade_two = models.ForeignKey(Trade, on_delete=models.CASCADE, related_name='trade_two', db_column='trade_two') status = models.TextField(default='Waiting for 2nd confirmation') def get_transaction_name(self): return ''.join([self.trade_one_id, ' and ', self.trade_two_id, ' on ', timezone.now().strftime("%b %d, %Y %H:%M:%S UTC"), ')']) def save(self, *args, **kwargs): self.name = self.get_transaction_name() super(Transaction, self).save(*args, **kwargs) def __str__(self): return self.name def get_absolute_url(self): return reverse('confirmed-trade', kwargs={'pk': self.pk}) views.py: def insert_transaction(request): if 'trade_1_id' not in request.POST or 'trade_2_id' not … -
Django print not printing when i "runserver"
i have this program, it used to work (print in th console) but it doesn't anymore i want to figure out why ! This is my views.py : import requests import os import json from django.http import JsonResponse, HttpResponse from django.shortcuts import render def btc(request): query_url = [ 'https://api.blockchair.com/bitcoin/stats', ] headers = { } result = list(requests.get(u, headers=headers) for u in query_url) json_data1 = result[0].json() data = [] data.append(json_data1['data']['transactions']) print(data) context = { "data": data, } return render(request, "index.html", context) it used to print the "data" values in the console when i do python manage.py runserver any idea on how to fix it ? -
What to choose for web development, Django or Laravel?
I'm new here and this is my first Question. I'm going to start web development. But I'm confused that what to start, Pyhthon(Django) or Php(larave) ? Help me plz... -
Django migrate app zero does not drop tables
I understand that all migrations applied to an app can be reversed using "migrate <app_name> zero". In the migration folder for the app, there are two migration files. However the below shows "No migrations to apply". And afterward when trying to run "migrate <app_name>" the database is returning an error saying that there is already an object of the name. Can someone help me understand what is happening here? Why is "migrate <app_name> zero" not seeing the two migrations that need to be reversed. C:\Users\...\mysite>python manage.py migrate awards zero Operations to perform: Unapply all migrations: awards Running migrations: No migrations to apply. C:\Users\...\mysite>python manage.py migrate awards Operations to perform: Apply all migrations: awards Running migrations: Applying awards.0001_initial...Traceback (most recent call last): File "C:\Program Files\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql) File "C:\Program Files\Python38\lib\site-packages\sql_server\pyodbc\base.py", line 553, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42S01', "[42S01] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]There is already an object named 'awards_student' in the database. (2714) (SQLExecDirectW)") Thank you! -
After I submit form with uploading photos, there are nothing to save on Django database
I met a problem. When I choose a photo as a profile_pic on the registration page, it saves any information without a photo. But I can't find out why it didn't work. There is nothing in the Profile pic after submitting. setting.py """ Django settings for learning_templates project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR=os.path.join(BASE_DIR,'templates') STATIC_DIR=os.path.join(BASE_DIR,'static') MEDIA_DIR=os.path.join(BASE_DIR,'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pgmh_#pcqd(3sf(a3oj#^vyv4l-#p6g=n-=^!z)0d@!k)!_ear' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'basic_app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'learning_templates.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], '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', ], }, }, ] WSGI_APPLICATION = 'learning_templates.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { … -
Django image not storing
I am trying to upload the image of desktop to the server using ModelView. It's storing link into the database but image is not getting uploaded into the MEDIA folder. Models: class File(models.Model): # file = models.FileField(blank=False, null=False) file = models.ImageField(upload_to='media/', blank=True) remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) URL: path('upload/', views.FileView.as_view(), name='file-upload'), Serializer: class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields="__all__" View: class FileView(generics.ListCreateAPIView): queryset = File.objects.all() serializer_class = FileSerializer Global settings: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Output: "id": 18, "file": "https://<URL>/media/home/tguser/tgportal/core/media/check.png", "remark": "ok", "timestamp": "2021-03-19T16:43:50.131435Z" } The file link is generating but no file uploded at that location. Any help appreciated. PD -
DJANGO Problem at rendering Form - Dropdownlist not show
When I rendering {{form.as_p}}: all input text is fine display as expected (from model.CharField) all select option just showing label without dropdownlist (from model.ForeignKey) but when i use w3shool html editor, copying code from view page source html and paste in w3.html editor all is fine, select option is appear on that. So, What is wrong? please help me get the answer, and fix the problem thank you models.py class Project(models.Model): project_no = models.CharField(max_length=10, blank=True) project_name = models.CharField(max_length=100, blank=True) project_no_file = models.CharField(max_length=10, blank=True) project_div = models.ForeignKey(Division, on_delete=models.CASCADE) project_cord = models.ForeignKey(Inspector, on_delete=models.CASCADE) def __str__(self): return self.project_no class Inspector(models.Model): inspector_name = models.CharField(max_length=50, blank=True) inspector_biro = models.ForeignKey(Biro, on_delete=models.CASCADE) def __str__(self): return self.inspector_name class Division(models.Model): div_name = models.CharField(max_length=50, blank=True) def __str__(self): return self.div_name views.py class AddView(CreateView): template_name = "launching/adddata.html" model = Project fields = '__all__' urls.py re_path(r'^project/add/$', AddView.as_view(), name='create') adddata.html <div class="container"> <form method="post" enctype="multipart/form-data" name="form_add"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> </div> result in browser dropdownlist for Project div and project cord not show result in W3.editor all is fine when its run the rendering code in w3editor -
Is this code correct to send email (django)?
Test.py email = EmailMessage() email['from'] = 'Your Name' email['to'] = 'name@gmail.com' email['subject'] = 'Welcome to Ourr Website!' email.set_content("Hope You are doingg great.") with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: smtp.ehlo() smtp.starttls() smtp.login('example@gmail.com', 'password: ********') smtp.send_message(email) print("Done") When I exicute I'm getting timeout error(10060), can any one help Thank out