Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't open lib ODBC Driver 17 for SQL Server On Django Docker
I try to access to connect sql server admin site With Docker I got the following error: DockerFile FROM python:3.6-alpine RUN apk update RUN apk add gcc libc-dev g++ libffi-dev libxml2 unixodbc-dev mariadb-dev postgresql-dev ENV PYTHONUNBUFFERED l RUN apk update && apk add build-base unixodbc-dev freetds-dev RUN pip install pyodbc RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ EXPOSE $PORT CMD ["manage.py runserver 0.0.0.0:$PORT"] How to fix this? -
Django cms remove href attribute from Textplugin
Currently I am working with Django-CMS & trying to add below code in Text Plugin. <a href="javascript:void(0);" id="map-world">Click me!</a> but django-cms automatically remove href attribute from text plugin and after save Text plugin has below content. <a id="map-world">Click me!</a> As a solution I have already tried below options which I have got from online search. TEXT_ADDITIONAL_TAGS = ('iframe', 'div', 'a') TEXT_ADDITIONAL_ATTRIBUTES = ('href', 'onclick') TEXT_HTML_SANITIZE = False but still not any solution working. Please let me know if anyone have solution. Thanks. -
django query set filter anf get the last item and first item
first_order = Order.objects.filter(user_id=request.user).first() last_order = Order.objects.filter(user_id=request.user).last() i have tried this but both are showing me the same things models.py class Order(models.Model): class Meta: ordering = ('-order_date1',) STATUS = ( ('Return', 'Return'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ('new order', 'new order'), ('hold', 'hold'), ) order_id= models.CharField(max_length=120, blank= True) user = models.ForeignKey(User,on_delete=models.CASCADE, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True , choices=STATUS, default='new order',blank=True) note = models.CharField(max_length=1000, null=True,blank=True) receiver_name= models.CharField(max_length=100) receiver_address= models.CharField(max_length=200) receiver_phone = models.CharField(max_length=50) order_number = models.CharField(max_length=50) condition= models.IntegerField(blank=True,default=0,null=True) order_date1 = models.DateField(auto_now_add=True,null=True) delivery_cost = models.IntegerField(default=60,null=True,blank=True) def __str__(self): return self.user.username -
Change AWS S3 File Path naming convetion Django Storage
A S3 Bucket URL format of a bucket is either of below two options: http://s3.amazonaws.com/[bucket_name]/ http://[bucket_name].s3.amazonaws.com/ I am using django storages to store files in S3. When I am fetching files in one of my deployment the s3 url format is like number 1 in above list and in other deployment it is of format 2. I checked all the settings, but everything seems to be same. Is there a way to set this convention or any way to keep this consistent. -
How to make postgres database accessible to another system?
So I'm using Django and Postgres for my project. I am new to integrating database using postgres with django. I connected the django project to my postgres database on my system.However, I want another person to manage the database and hence allow access to him to my database. I can see the tables through pgadmin 4 in my system, all of it being password protected and exclusive to my system. How can another person access this database using his pgadmin and his own password? For eg-dbsqlite has a file which is stored in project folder, which when shared can be accessed by another person with whom I share the code and project folder. Is such a thing possible with postgres using pgadmin administrator? If not how would I make this possible? -
Pagination for Django
I tried to install pagination into Django app. Django page displays the first 3 items at 1st page, but when I tried to go the next page, nothing was shown at 2nd page. I want to show 3 items each page, what should I do? Here are my codes. urls.py urlpatterns = [ path('', views.find,name='find'), path('<int:num>', views.find, name='find') ] views.py def find(request,num=1): if (request.method == 'POST'): msg = request.POST['find'] form = FindForm(request.POST) sql = 'select * from test_eu' if (msg != ''): sql += " where eng_discription ~ '.*" + msg +".*' ORDER BY image_amount DESC " data =TestEu.objects.raw(sql) page = Paginator(data,3) msg = sql else: msg = 'search words...' form = FindForm() data = "" page = Paginator(data,3) params = { 'title': 'Search Customs Rulings', 'message': msg, 'form':form, 'data': page.get_page(num), } return render(request, 'db/find.html', params) find.html ...... <ul class="pagination"> {% if data.has_previous %} <li class="page-item"> <a class="page-link" href="{% url 'find' %}"> &laquo; first</a> </li> <li class="page-item"> <a class="page-link" href="{% url 'find' %}{{data.previous_page_number}}"> &laquo; prev</a> </li> {% else %} <li class="page-item"> <a class="page-link"> &laquo; first</a> </li> <li class="page-item"> <a class="page-link"> &laquo; prev</a> </li> {% endif %} <li class="page-item"> <a class="page-link"> {{data.number}}/{{data.paginator.num_pages}}</a> </li> {% if data.has_next %} <li class="page-item"> <a class="page-link" … -
Can I use django fileds values in def functions?
I am trying to make a function to resize images before upload. I found something on interent and it is working but I want to improve it. Instead of having the output_size = (320, 560) [as default value always] I would like to have some django fields and change it every time I need from django admin. This is why I added image_height and image_width fields. In my way of thinking doing this was the solution output_size = (image_height, image_width) but it doesnt work output_size = (image_height, image_width) NameError: name 'image_height' is not defined How can I use image_height and image_width fields and use add the values to output_size My models.py from __future__ import unicode_literals from django.db import models from django.urls import reverse from PIL import Image def upload_location(instance, filename): return "%s/%s" %('image/service', filename) # Create your models here. class Services(models.Model): title = models.CharField(max_length=120) content = models.TextField(null=True, blank=True) image = models.ImageField(upload_to=upload_location, blank=True, null=True) image_height = models.PositiveIntegerField(default=320) image_width = models.PositiveIntegerField(default=560) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 320 or img.weight > 560: output_size = (image_height, image_width) img.thumbnail(output_size) img.save(self.image.path) def __unicode__(self): return self.title def __str__(self): return self.title -
Django Accessing external Database to get data into project database
i'm looking for a "best-practice" guide/solution to the following situation. I have a Django project with a MySql DB which i created and manage. I have to import data, every 5 minutes, from a second (external, not managed by me) db in order to do some actions. I have read rights for the external db and all the necessary information. I have read the django docs regarding the usage of multiple database: register the db in settings.py, migrate using the --database flag, query/access data by routing to the db (short version) and multiple question on this matter on stackoverflow. So my plan is: Register the second database in settings.py, use inspectdb to add to the model, migrate, define a method which reads data from the external db and add it to the internal (own) db. However I do have some questions: Do i have to register the external db if i don't manage it? (Most probably yes in order to use ORM or the cursors to access the data) How can i migrate the model if I don't manage the DB and don't have write permissions? I also don't need all the tables (around 250, but only 5 needed). (is … -
command ERROR(python,django,firebase) ********** pip install firebase-admin
enter image description here while i'm doing Django App Backend setting, there is a simple package to include firebase in Django app. Name is firebase-admin. So I tried to install the package with the following command ( $ pip install firebase-admin ) but there is an Error to operate the command. I've been Googling, but it's no use. PLZ let me know -
How to show PointField in django admin panel as lat and long
Despite the fact that I read a lot similar posts on how to show PointField as latitude and longitude in admin django panel I can not figure out how to do it. The admin panel keeps showing the map but not the desired two fields. Here is my unsuccessful trial using a LatLongWidget widget. my model: class Station(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) owner = models.ForeignKey(User, related_name="stations", on_delete=models.CASCADE) name =models.CharField(max_length=100) location = models.PointField() my admin.py from django.contrib import admin from django.contrib.gis.admin import OSMGeoAdmin from .models import Station from django.contrib.gis.db import models as geomodels from .widgets import LatLongWidget @admin.register(Station) class StationAdmin(OSMGeoAdmin): list_display = ('name', 'owner','location') search_fields = ('name','owner__email') formfield_overrides = { geomodels.PointField: {'widget': LatLongWidget}, } my widget.py from django import forms from django.contrib.gis.db import models as geomodels class LatLongWidget(forms.MultiWidget): """ A Widget that splits Point input into latitude/longitude text inputs. """ def __init__(self, attrs=None, date_format=None, time_format=None): widgets = (forms.TextInput(attrs=attrs), forms.TextInput(attrs=attrs)) super(LatLongWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return tuple(value.coords) return (None, None) def value_from_datadict(self, data, files, name): mylat = data[name + '_0'] mylong = data[name + '_1'] try: point = Point(float(mylat), float(mylong)) except ValueError: return '' return point How can I rid of map and have lat and long instead? -
u'articles' is not a registered namespac
I've been struggling to deal with this error for days, I would really appreciate if anyone could assist, I tried so many different suggestions online and all in vain: I'm using Django 1.8.2, (python 2.7.10) and followed the example to the the T and yet I still get the following error: NoReverseMatch at /accounts/login/ u'articles' is not a registered namespace Request Method: POST Request URL: http://localhost:8000/accounts/login/ Django Version: 1.8.2 Exception Type: NoReverseMatch Exception Value: u'articles' is not a registered namespace Exception Location: /Library/Python/2.7/site-packages/django/core/urlresolvers.py in reverse, line 575 Python Executable: /usr/bin/python Python Version: 2.7.10 Python Path: ['/Users/mac/django-playlist/djangonautic', '/Library/Python/2.7/site-packages/pip-19.3.1-py2.7.egg', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Library/Python/2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC'] My urls.py: from django.conf.urls import include, url from django.contrib import admin from .import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/',admin.site.urls), url(r'^accounts/$',views.about), url(r'^accounts/',include('accounts.urls')), url(r'^articles/',include('articles.urls')), url(r'^about/$',views.about), url(r'^services/$',views.services), url(r'^$',views.homepage), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and my accounts/url.py from django.conf.urls import url from .import views app_name = 'accounts' app_name = 'articles' urlpatterns = [ url(r'^signup/$', views.signup_view, name="signup"), url(r'^login/$', views.login_view, name="login"), ] accounts/views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm # Create your views here. def signup_view(request): if request.method =='POST': form=UserCreationForm(request.POST) … -
My charts doesn't work after inserting X-axis
Please if you have successfully worked on months or other time like years days in django chartjs, please kindly share a link where i can see how it is utilized. As i can't figure why mine isn't working, the moment i put the x-axis it doesn't show any data. But if i remove the x-axis part, it works perfectly. my main aim is to make the months display so i can get some data into it. Any help eould be really appreciated. Below is my script file. <script> $(document).ready(function(){ var ctx2 = document.getElementById('myChart2'); var myChart2 = new Chart(ctx2, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: 'counts of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }], xAxes: [{type: 'time', position: 'bottom', time: { … -
Architecting models and serializers for posting and getting optional fields properly in django rest framework
As you see on my models I have some Many2Many relationship and inheritance. I would like to make post request for Bid by sending one of my related datas(context_set or contextdoubled_set) optionally. I have structured like the following and it works as I wanted. Is there any better idea to restructure for making GET/POST request optionally ? I want to architect my code flexible, clean and good. Thanks in advance. models.py class Brand(models.Model): name = models.CharField(max_length=100) class Meta: db_table = "t_brand" def __str__(self): return self.name class BrandDoubled(models.Model): name = models.CharField(max_length=100) brands = models.ManyToManyField(Brand) class Meta: db_table = "t_brand_doubled" class Bid(models.Model): class Meta: db_table = 't_bid' class BaseContext(models.Model): bid = models.ForeignKey(Bid, on_delete=models.CASCADE) class Meta: abstract = True class Context(BaseContext): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) class Meta: db_table = 't_context' def __str__(self): return f"Context {self.brand}" class ContextDoubled(BaseContext): brand_doubled = models.ForeignKey(BrandDoubled, on_delete=models.CASCADE) class Meta: db_table = 't_context_doubled' def __str__(self): return f"ContextDoubled {self.brand_doubled}" serializers.py from .models import * class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand fields = '__all__' class BrandDoubledSerializer(serializers.ModelSerializer): class Meta: model = BrandDoubled fields = '__all__' class ContextHelper(serializers.ModelSerializer): class Meta: model = Context fields = ('brand',) class ContextDoubledHelper(serializers.ModelSerializer): class Meta: model = ContextDoubled fields = ('brand_doubled',) class BidPostSerializer(serializers.ModelSerializer): context_set = ContextHelper(many=True, required=False) contextdoubled_set … -
Django - Rest Framework API password reset mail with a security code
Basically i want to do an api for mobile app so user can reset their password from there with entering that secure code to the form. My problem is, i cant find a way to add to "secure code" field which will held in database, or sending that code with the link in email. Should i override or rewrite all auth reset password methods? I was able to use api for my other fields but I'm kinda lost in resetting password part, any help would be great. Thanks. -
Django filter foreign key relationships by user group
I'm trying to filter activities in a task (list of activities) by the assigned user group. TaskActivityModel.objects.filter(activity__workCenter=request.user.groups) this gives me a TypeError: Field 'id' expected a number when I amend the filter parameter to request.user.groups.id I get an AttributeError: 'ManyRelatedManager' object has no attribute 'id'. What am I missing? Each activity has a single group assigned to it. The users can be a in many groups. Could this be the issue TaskActivityModel class TaskActivityModel(models.Model): task = models.ForeignKey(TaskModel, on_delete=models.PROTECT) activity = models.ForeignKey(ActivityModel, on_delete=models.PROTECT) startTime = models.DateTimeField(default=timezone.now) finishTime = models.DateTimeField(null=True) ActivityModel class ActivityModel(models.Model): activityName = models.CharField(max_length=100) description = models.CharField(max_length=200) workCenter = models.ForeignKey(Group, on_delete=models.PROTECT) history = HistoricalRecords() -
Heroku Django app returning error heroku/router: at=error code=H10 desc=“App crashed”
I have this error: 2020-09-17T07:07:36.335288+00:00 app[web.1]: 2020-09-17T07:07:36.335288+00:00 app[web.1]: Traceback (most recent call last): 2020-09-17T07:07:36.335312+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 8, in 2020-09-17T07:07:36.335449+00:00 app[web.1]: sys.exit(run()) 2020-09-17T07:07:36.335453+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in run 2020-09-17T07:07:36.335595+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2020-09-17T07:07:36.335596+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 228, in run 2020-09-17T07:07:36.335787+00:00 app[web.1]: super().run() 2020-09-17T07:07:36.335788+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 72, in run 2020-09-17T07:07:36.335922+00:00 app[web.1]: Arbiter(self).run() 2020-09-17T07:07:36.335926+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 229, in run 2020-09-17T07:07:36.336109+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2020-09-17T07:07:36.336113+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 342, in halt 2020-09-17T07:07:36.336335+00:00 app[web.1]: self.stop() 2020-09-17T07:07:36.336339+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop 2020-09-17T07:07:36.336578+00:00 app[web.1]: time.sleep(0.1) 2020-09-17T07:07:36.336583+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld 2020-09-17T07:07:36.336761+00:00 app[web.1]: self.reap_workers() 2020-09-17T07:07:36.336762+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2020-09-17T07:07:36.337032+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2020-09-17T07:07:36.337053+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2020-09-17T07:07:36.404250+00:00 heroku[web.1]: Process exited with status 1 2020-09-17T07:07:36.445859+00:00 heroku[web.1]: State changed from up to crashed 2020-09-17T07:08:11.522892+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=mocaweb.herokuapp.com request_id=a1f3c1a6-e687-44b2-9478-497f1bc64637 fwd="181.170.115.80" dyno= connect= service= status=503 bytes= protocol=https Procfile: web: gunicorn djecommerce.wsgi wgsi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djecommerce.settings') application = get_wsgi_application() -
django email not sending ( using form )
from django.http import HttpResponse, HttpResponseRedirect from .forms import Contact from django.core.mail import send_mail def contact(response): if response.method=="POST": form= Contact(response.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] comment = form.cleaned_data['comment'] subject= "COMMENTS" send_mail(subject,comment,email,['nafiyadargaw360@gmail.com'],fail_silently=True) return HttpResponseRedirect("/contact") else: form=Contact() context = {'form': form} template = 'contact/index.html' return render(response,template,context) i get no error when i fill in the form but first the page doesnt redirect to /contact as told but when i try that using shell it works -
How to edited data post in python django without page refresh using javascript without ajax and jquery?
Here I upload my HTML and js file. [when I click the edit button it will open the corresponding data and I want to edit this data and post it again without refresh the page in python Django using the javascript ][1] index.html <div class="row"> <div class="col-md-12"> <div class="card shadow-lg"> <div class="card-body"> <div class="row"> <div class="col-md-6"> <h5 class="card-title"><i class="fa fa-user-circle" aria-hidden="true"></i> <a href="{% url 'profile' datas.id %}">{{datas.user_id|capfirst}}</a></h5> </div> <div class=" col-md-6 text-right" > {% if request.user.id == datas.user_id_id %} <button id="edit" value="{{datas.post}}" onclick="edit(this)">Edit</button> <input type="hidden" value="{{datas.id}}" > {% endif %} </div> </div> <div id="msg"> <hr> {{datas.post}} <hr> </div> <div class="row"> <div class="col-md-4"><i class="fa fa-thumbs-up"></i></div> <div class="col-md-4"></div> <div class="col-md-4 text-right">{{datas.post_date}}</div> </div> </div> </div> </div> </div> <br> {% endfor %}``` **inbox.js** ```function edit(id) { var body = id.value; var parentcard = id.closest(".card-body") parentcard.querySelector("#msg").innerHTML = '<form id="postData">'+ '<div class="form-group">'+ '<textarea class="form-control" name="edit_post" rows="3" id="body">'+body+'</textarea>'+ '</div>'+ '<button class="btn btn-primary" type="submit">POST</button>'+ '</form>'; }``` [1]: https://i.stack.imgur.com/OTEIf.jpg -
Get user object from simple API call without a viewset in Django 3.0.3 using rest_framework_jwt
I want to retrieve the user object in order to check if the user is allowed to access a file or not in a web app based on Django and rest_framework_jwt for the REST WebServices. I have the following settings for my web app: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_PAGINATION_CLASS':'swiftapp.custom_pagination.CustomPagination', } MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] My defined routing: router = routers.DefaultRouter(trailing_slash=False) #router.register(r'operation/<str:branch>/<str:filename>/', SwiftFileViewSet, basename='get_queryset') # This didn't work and I don't need a Viewset anyways router.register(r'operations/(?P<start_date>\d{4}-\d{2}-\d{2})/(?P<end_date>\d{4}-\d{2}-\d{2})$', OperationViewSet, basename='get_queryset') urlpatterns = [ path(r'api/', include(router.urls)), path('api/operation/<str:branch>/<str:filename>/', get_operation, name='get_operation'), ] In the ModelViewset below (GET method), I'm able to get the authentified user object: class OperationViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) authentication_classes = (authentication.JSONWebTokenAuthentication,) queryset = Operation.objects.all() serializer_class = serializers.OperationSerializer permission_classes = (ReadOnly,) def perform_create(self, serializer): serializer.save(user=self.request.user) def get_queryset(self): user = self.request.user # I can get the user object here logger.warning("logged user", user) req = self.request.data queryset = Operation.objects.filter(branch=user.get_branch(), date__gte=self.kwargs.get('start_date'),date__lte=self.kwargs.get('end_date')) return list(queryset) but not in this simple GET API controller: def get_operation(request, section, filename): authentication_classes = (authentication.JSONWebTokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) user = self.request.user # I cannot get the user object here logger.warning("logged user", user) with open("C:\\operations\\" + section + "\\" … -
Adding data in Postgresql shows in localhost but not on server
I have a project on django python, using PostgreSQL as my DB, AWS for server hosting and Elastic Beanstalk for envoirnment deployment. When I am adding any objects in one of my Model from the server it is not visible there but it is visible on my localhost in the same table. When I am adding any objects from localhost it is again not visible on server but visible on localhost. Although when I deploy my enviornment again, it shows up on the server. I have tried this Django query does not update when database changes but it doesn't worked for me. obj.refresh_from_db() I have checked my settings all the DB settings are correctly mentioned there. P.S: I am using bootstrap-table and getting the data from server side. -
Handling csrf failures in django
I have to read csrf failure message from request page and redirect to custom page with proper messages. def csrf_failure(request, reason=""): ctx = {'message': 'csrf failure'} print('****************************************') content = request print(content) if 'Forbidden (CSRF token missing or incorrect.)' in content: print(request) return HttpResponseRedirect('/login', ctx) else: raise PermissionDenied -
(Django REST Framework) Adding field to a model at creation time
I'm making a weather api. I have 2 models: Location and Parameters. Parameters are properties like humidity, temperature, etc of Location. When I added a Location, I also want to add some default Parameters to it. When the new Location is displayed, I want an Aggregation field to be shown which is the Average, Sum, Min and Max of the available parameters. My problem is I'm saving the new Location before adding default Parameters so the Aggregation field of the Location doesn't have any data about the its Parameter values. Could I do something like after creating the default Parameters, go back to Location and somehow add the Aggregation? I really appreciate any help!! Here is what I did: Models class Location(models.Model): name = models.CharField(max_length=25, unique=True) description = models.CharField(max_length=64, blank=True) longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) class Meta: verbose_name_plural = 'locations' def __str__(self): return self.name class Parameter(models.Model): name = models.CharField(max_length=25) unit = models.CharField(max_length=10, blank=True) values = models.JSONField(default=list, blank=True) _location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="parameters" ) def __str__(self): return self.name Serializers from .helper import add_location, aggregate, get_parameter_values, add_parameter class ParameterSerializer(serializers.ModelSerializer): aggregation = serializers.SerializerMethodField() class Meta: model = Parameter fields = ('id', 'name', 'unit', 'aggregation', 'values') def get_aggregation(self, obj): return aggregate(obj.values) … -
How to access to subdirectory on django?
how to access to subdirectory on django? I made django app which include 2 views, "/" and "/config". http://example.com/ http://example.com/config It's can use on "python manage.py runserver". So I try to deploy it to Apache on Windows10. Then problem occurred. App can view "http://example.com/" , but it can't view "http://example.com/config". Browser display "Forbidden". so I think it's access parmission probrem. First I check it's directory's owner/parmission mistake. But OS is Windows. So I think it isn't cause. How can I use app on Apache on Windows10 ? 【enviroment】 Windows10 Apache 2.4.41 django 3.0.8 Python 3.7.3 【Directory(httpd.conf)】 <Directory C:/apps/mysite/appname> <Files wsgi.py> Require all granted </Files> </Directory> 【urlpatterns】 urlpatterns = [ path('', views.index, name='index'), path('config', views.config, name='config'), ] -
Redirect to function based detail view after submitting form
I created a model named Student. I created a model form. I want to go to detail view not the list view, after submitting model form. How do i do that ? model.py class Student(models.Model): student_name = models.CharField(max_length=100) father_name = models.CharField(max_length=100) forms.py class AdmissionForm(forms.ModelForm): class Meta: model = Student fields = '__all__' views.py def admission_form(request): form = AdmissionForm() if request.method == 'POST': form = AdmissionForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('student-list') # i want to redirect to detail view context = {'form':form} return render(request, 'student/admission_form.html', context) In this admission form, i want to redirect to detail view of the student not the list view. How can i do that. In this code, i have redirected to list view. def student_detail(request, id): stud = Student.objects.get(id=id) context = {'stud':stud} return render(request, 'student/student_detail.html', context) urls.py urlpatterns = [ path('admission_form/', views.admission_form, name = 'admission-form'), path('student/', views.student_list, name = 'student-list'), path('student/<int:id>/', views.student_detail, name = 'student-detail'), ] -
Django generate FTP download link
I have a model which contains a FileField that is connected to a FTP server (using this doc). Files are uploaded using Django admin. I want to provide a download link to each file for the site visitors. I can simply use href = "ftp://<username>:<pass>@<host>/path/to/file" but this way visitors can see my credentials. I need a way to create this download link more secure. this is my model: fs = ftp.FTPStorage() class Video(models.Model): video_file_ftp = models.FileField(upload_to = 'srv/videos/', storage=fs)