Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tracking the cab, system with realtime updates. Suggestions for implementaion
I want to make one system/dashboard to track the cabs: It would show vehicles’ real-time location(markers should move along with each cab) on the Google maps. It would show vehicle status; running, stopped, and scheduled, shown in different colors on the Google maps and the sidebar. The sidebar should have Driver Name, Contact, Vehicle Number, Distance Covered, Start Time, Last Updated, Last Stoppage and other relevant details. Kindly, give the suggestion for efficient implementation. Which platforms to use and also the flow of data from the database(having information about the driver and vehicle) to the dashboard. -
models.DateTimeField() Time is always 1 hour less
below is part of the code of my django models.Model class. If I set in admin panel for example 17.03.2018 14:00 it saves correctly this model with correct date and time. But if I print result it returns one hour less 17.03.2018 13:00. How can i fix it? ... starts_at = models.DateTimeField() ... beginnt_date = json.dumps(starts_at.date().strftime("%d-%m-%Y"), cls=DjangoJSONEncoder) beginnt_zeit = json.dumps(starts_at.time().strftime("%H:%M"), cls=DjangoJSONEncoder) result = [] result.append({ 'beginnt_date': beginnt_date, 'beginnt_zeit': beginnt_zeit, }) print(result) >>> [{'beginnt_date':"17-03-2018", 'beginnt_zeit':"12:38"}] -
get_context_data function in the Detailview even didn't call but still could call the context
**I have commented the get_context_data function, but in the template, i could call {{ object }} , could anyone please explain this ** # def get_context_data(self, *args,**kwargs): # context=super(productdetailview,self).get_context_data(*args,**kwargs) # print(context) # print(self.kwargs.get("pk")) # return context Here the whole code class ProductDetailSlugView(DetailView): queryset = product.objects.all() template_name = "product/detail.html" print(queryset) # def get_context_data(self, *args,**kwargs): # context=super(productdetailview,self).get_context_data(*args,**kwargs) # print(context) # print(self.kwargs.get("pk")) # return context # def get_context_data(self, *args, **kwargs): # context=super(ProductDetailSlugView,self).get_context_data(*args,**kwargs) # context['cart']=cart.objects.get_or_create(self.request) # # print(context) # return context # def get_object(self, *args,**kwargs): # print(args) # print(kwargs) # pk=self.kwargs.get("pk") # slug=self.kwargs.get("slug") # print(self.kwargs.get("slug")) # print(product.objects.get_by_slug(slug)) # return product.objects.get_by_slug(slug) -
How to use django custom filter in a listview to check if a related data exists in that object?
I'm having a problem. Suppose, you've two model:- 'Problem' and 'Solve' Problem model:- class Problem(models.Model): problem_name = models.CharField(max_length=20) slug = models.SlugField(max_length=100, unique=True) Solve model(I'm storing the User and Problem as a new model if current user solves a problem):- class Solve(models.Model): problem = models.ForeignKey(Problem, on_delete=models.CASCADE, related_name="solved") solver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="solved") This is my problem's listview:- class ProblemList(generic.ListView): model = Problem context_object_name = 'all_problems' template_name = 'problems/problem_list.html' Where the html file contains a segment:- {% if all_problems %} {% for problem in all_problems %} <h3><li><a href="{% url 'problems:problem_detail' slug=problem.slug %}">{{ problem }}</a>{% if user.is_authenticated and **problem is solved by the current user** %}Solved{% endif %}</li></h3> {% endfor %} {% else %} <h3>No problems added yet</h3> {% endif %} Where, on the 3rd line( This part:- " problem is solved by the current user ") I am trying to show if the authenticated user has solved the problem or not "For each of the problems in the listView". How do I do that? I've tried this in the template:- {% if user.is_authenticated and problem|is_solved_by_user:'user' %}Solved{% endif %} and the below code inside the Problem Model class(I've tried putting the same code inside listview class):- from django import template register = template.Library() … -
access path url parameter in view in Django
I'm using Django 2.0 I have two modesl course and chapter I want to pass course.pk in CreateView of chapter since chapter is related to course. This is my urls.py from django.urls import path from courses.views import Courses, NewCourse, CourseView, NewChapter app_name = 'course' urlpatterns = [ path('all', Courses.as_view(), name='list'), path('new', NewCourse.as_view(), name='new'), path('<pk>/detail', CourseView.as_view(), name='detail'), path('<course_id>/chapter/add', NewChapter.as_view(), name='new_chapter') ] and NewChapter(CreateView) class NewChapter(CreateView): template_name = 'courses/chapter/new_chapter.html' model = Chapter fields = ['name'] def get_context_data(self, **kwargs): context = super(NewChapter, self).get_context_data(**kwargs) course = Course.objects.get(pk=kwargs['course_id']) if course is None: messages.error(self.request, 'Course not found') return reverse('course:list') return context def form_valid(self, form): form.instance.created_by = self.request.user form.instance.course = Course.objects.get(pk=self.kwargs['course_id']) form.save() I also want to carry on validation if the Course with passed course_id exists or not. If it does not exists user will be redirected back otherwise he will be able to add chapter to it. But it is giving error as KeyError at /course/9080565f-76f4-480a-9446-10f88d1bdc8d/chapter/add 'course_id' How to access parameters of path url in view? -
Applying migrations in views.py if form.is_valid() doesn't work
I'm trying to run migrations if submitted form is valid, but the migrations are not detected after first form submit. However if I submit the valid form once again, the migrations from previous submit are ran normally. I also tried with request_finished signal, but the behavior is completely the same. views.py def factory(request): factory_form = FactoryForm(request.POST or None) if factory_form.is_valid(): # Here I change models.py via python file handling return HttpResponseRedirect(reverse('factory:run_migrations')) context = { 'factory_form': factory_form } return render(request, 'factory/factory.html', context) def run_migrations(request): from django.core import management management.call_command('makemigrations') management.call_command('migrate') return HttpResponseRedirect(reverse('factory:factory')) -
Passing Two Models in a Single View
I'm trying to show information from two models, in a single view in a Django project. I have 2 models: Main (parent), Visits (child) I would like to show a details view of Main (name, date of birth) and then show a list of the Visits. Effectively, show one record from parent table, and all the related children tables. But the children tables are only partially showing up (see the image). Also, can someone tell me how the Django code knows to render only the child records that are associated with the parent record (where/when are foreign keys filtered?) Image showing the problem eg: Main.name Visit.date - Visit.type Visit.date - Visit.type Visit.date - Visit.type views.py class MainDetailView(generic.DetailView): model = Main template_name = "myapp/main-detail.html" def get_context_data(self, **kwargs): context = super(MainDetailView, self).get_context_data(**kwargs) context['visit'] = Visit.objects.all() # And so on for more models return context models.py class Visit(models.Model): fk_visit_patient = models.ForeignKey(Main, on_delete=models.CASCADE, verbose_name=('Patient Name')) visit_date = models.DateField() visit_label = models.CharField(max_length=256, blank=True, null=True) visit_specialty_list = ( (str(1), 'General Practice'), (str(2), 'Internal Medicine'), (str(3), 'Surgery'), visit_specialty = models.CharField( max_length=256, choices=visit_specialty_list, default=1, ) def __str__(self): return str(self.visit_label) def get_absolute_url(self): return reverse('myapp:main-detail', kwargs={'pk': self.pk}) template.html <div class="container-fluid"> <div class="row"> <div class="col-sm-12 col-md-7"> <div class="'panel panel-default"> <div class="panel-body"> … -
Asyncio in Django
I'm using a module that performs asyncio functions to obtain comments through scraping, the code works perfectly in Python scripts but Django does not seem to execute the Asyncio code. def comments(request): if request.method == 'POST': async def main(): q = Query('Donald Trump', limit=20) async for tw in q.get_comments(): print(tw) loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) loop.run_until_complete(loop.shutdown_asyncgens()) finally: loop.close() form = CommentForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/index.html') else: form = CommentForm() return render(request, 'index.html', {'form': form}) With some dirty threading work with Asyncio inside of threads, I'm able to execute the loop, but only once. -
django rest framwork Error decoding signature with jwt RS256
im using django rest framwork with jwt in setting i used RS256 ALGORITHM i want send token after user authenticated this is my function im trying send token with user_id and is_user data it will produce token but when i pass token in request to server server response : detail : "Error decoding signature." why?? JWT_SECRET = 'secret' JWT_ALGORITHM = 'HS256' JWT_EXP_DELTA_SECONDS = 20 def validate(self, data): user_obj = None email = data.get('email', None) username = data.get('username', None) password = data.get('password') if not email and not username: raise ValidationError("email or username is required!") if '@' in username: email = username user = User.objects.filter( Q(email=email) | Q(username=username) ).distinct() # user = user.exclude(email__isnull=True).exclude(email__iexact='') if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("this username/email is not valid") if user_obj: if not user_obj.check_password(password): raise ValidationError("password is incorrect") # payload_handler(user) # payload = payload_handler(user_obj) payload = { 'user_id': user_obj.id, 'is_user': True, } jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) # code = json_response({'token': jwt_token.decode('utf-8')}) data['token'] = jwt_token return data jwt setting: JWT_AUTH = { 'JWT_SECRET_KEY': SECRET_KEY, 'JWT_ALGORITHM': 'RS256', 'JWT_AUTH_HEADER_PREFIX': 'Bearer', 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=6600), } -
Django Rest Framework MySQL Tables renamed/add prefix
I'm beginner in Djang Rest Framework, and today I got some problem with models and mysql dabase. I got mysql table like this: Mysql View: models.py: from django.db import models class Reservation(models.Model): reservations = models.CharField(max_length=200) done = models.BooleanField() Structure of Catalogs: Structure of Catalogs Why when I migrate data to dabase, something add prefix to table name like: 'testsite_' Conlusion: I want to create models.py and migrate data to mysql datebase without this prefix 'testsite_' how it was in first image : inndb.testsite_reservation How Can I do this? -
Django custom filter in a listview to check if a related data exists in that object
Suppose, you've two model:- 'Problem' and 'Solve' Problem model:- class Problem(models.Model): problem_name = models.CharField(max_length=20) slug = models.SlugField(max_length=100, unique=True) Solve model(I'm storing the User and Problem as a new model if current user solves a problem):- class Solve(models.Model): problem = models.ForeignKey(Problem, on_delete=models.CASCADE, related_name="solved") solver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="solved") This is my problem's listview:- class ProblemList(generic.ListView): model = Problem context_object_name = 'all_problems' template_name = 'problems/problem_list.html' Where the html file contains a segment:- {% if all_problems %} {% for problem in all_problems %} <h3><li><a href="{% url 'problems:problem_detail' slug=problem.slug %}">{{ problem }}</a>{% if user.is_authenticated and **problem is solved by the current user** %}Solved{% endif %}</li></h3> {% endfor %} {% else %} <h3>No problems added yet</h3> {% endif %} Where, on the 3rd line( This part:- " problem is solved by the current user ") I am trying to show if the authenticated user has solved the problem or not "For each of the problems in the listView". How do I do that? I've tried this in the template:- {% if user.is_authenticated and problem|is_solved_by_user:'user' %}Solved{% endif %} and the below code inside the Problem Model class(I've tried putting the same code inside listview class):- from django import template register = template.Library() @register.filter def is_solved_by_user(self, user): … -
Could not find a version that satisfies the requirement cloud-init==17.1 (from -r requirements.txt (line 3)) (from versions: )
whenever I try to use this code errors comes out. enter code here (venv) root@ip-172-31-30-138:~# pip install -r requirements.txt The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. -
Does Django Automatically Sanitise urls for directory traversal attacks?
I have a view in my Django web app like this : def download_func(request, url): file_url = '/home/mylaptop/myproject/' + url file = open (file_url, "rb").read() response = HttpResponse(file, content_type="application/octect- stream") response['Content-Disposition'] = 'attachment; filename = %s' %url return response and a url conf like this : urlpatterns = [ ... url(r'^media/videos/(?P<url>[-._\w]+)/$', views.download_func), ... ] Downloading a video that is uploaded before is perfectly working, but my question is: "Is there the risk of directory traversal attack in my app?" if "yes" how can I fix it (or is there a better way of writting view for downloading while development?) I have been testing directory traversal on it and understood that Django automatically sanitises urls containing "../../" is that right? thanks -
Is it possible to use alpha vantage python index package on my django project?
I want to use alpha vantage python wrapper to my django project.How can i call built-in functionality from alpha vantage to my django project. -
Mocked unit test raises a "stop called on unstarted patcher" error
When running the test bellow, I got a stop called on unstarted patcher. def test_get_subvention_internal_no_triggered_admission(self): billing_cluster = BillingClusterFactory() subvention = SubventionFactory(billing_cluster=billing_cluster) convive_sub = ConviveFactory(subvention=subvention, billing_cluster=billing_cluster) order_5 = OrderFactory(beneficiary=convive_sub) order_operation_5 = CreationOrderOperationFactory(order=order_5) with patch('orders.models.Order.subvention_triggered_same_day', return_value=True): with patch('builtins.hasattr', return_value=False): self.assertIsNone(order_operation_5._get_subvention()) I read stuff about this error on stack overflow, and concluded that I should avoid mocking the same stuff (stacked mocks). But it's not what I'm doing here. I'm nesting mocks, and it seems to be ok. If I invert the return values (first mock returns False, second returns True), the test works well. Any idea? Thanks. -
Django save() override works in project shell and for the site form, but doesn't work in django admin
There is a model called Note. Detail view: def note_detail(request, pk): note = get_object_or_404(Note, id=pk) return render(request, 'note_detail.html', {'note': note}) I need to automate download of a note_detail.html with the newly created object. For this purpose I override model save(). def save(self, *args, **kwargs): super(Note, self).save(*args, **kwargs) print("{}".format(self.pk)) # prints the right pk note_pk = self.pk wget_url = "http://127.0.0.1:8000/note/{0}/".format(note_pk) wget_command = "wget {0} -O note-{1}.html".format( wget_url, note_pk) os.system(wget_command) Wget works fine when creating object in project shell and when submitting form on the site. But it doesn't work when a note is created in django admin. Traceback: 6 --2018-03-15 13:14:53-- http://127.0.0.1:8000/note/6/ Connecting to 127.0.0.1:8000... connected. HTTP request sent, awaiting response... 404 Not Found 2018-03-15 13:14:53 ERROR 404: Not Found. Whereas the link of the traceback is correctly rendered in browser. How to make save() override work for objects saved in admin? -
Custom ChoiceField in Serialiers - Django Rest Framework
I have an issue hope you guys help me. I want to have a ChoiceField with user field which choices = User who is participants and have last_name is 'Z'. My serializer: class ArticleCreateSerializer(ModelSerializer): user_choice = SerializerMethodField() user = ChoiceField(choices=user_choice) class Meta: model = Feed fields = [ 'id', 'user', 'post', 'participants' ] def get_user_choice(self, obj): user_choice = User.objects.filter(id=obj.participants, last_name='Z') return user_choice Error: TypeError: 'SerializerMethodField' object is not iterable -
Django - matplotlib image doesn't display
I am new to Django and I am trying to display a matplotlib image and some data in a view. The matplotlib is created in a different python file. Here is the matplotlib code: import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import numpy as np from django.http import HttpResponse, HttpResponseRedirect def plot_playoutcomes(playdata): fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) x = np.arange(-2,1.5,.01) y = np.sin(np.exp(2*x)) ax.plot(x, y) response = HttpResponse(content_type='image/png') canvas.print_png(response) return response It produces a simple graph. And here is views.py: def getinput(request): if request.method == 'POST': form = get_data(request.POST) if form.is_valid(): down = form.cleaned_data['get_down'] ytg = form.cleaned_data['get_ytg'] yfog = form.cleaned_data['get_yfog'] map_data = next_play.objects.filter(last_dwn__exact=down, last_yfog__exact=yfog, last_ytg__exact=ytg) fig = plot_playoutcomes(map_data) context = {'form': form, 'query_data': map_data, 'img': fig} return render(request, 'play_outcomes/output.html', context) else: form = get_data() return render(request, 'play_outcomes/getinput.html', {'form': form}) def output(request): return render(request, 'play_outcomes/output.html', context) It gets data from a form, uses that to query a dataset. Problem is that when I try to display the template the image {{img}} doesn't appear. On the webpage I get this: <HttpResponse status_code=200, "image/png"> but not image. Help! -
Hey! I am working in django and try to build a CRUD blog.And for that I have written a (clas
I am working in django and try to build a CRUD blog.And for that I have written a (class) name Article.But when I m executing,it prompts the Indentation error! Although it is not a big task but eventhough i m not able to do it!Pls help me to figure it out. -
Is there any way to connect Django to SQL Server?
Is there any way for connect Django to SQL Server ? I searched a lot for doing this and I can't find any thing for doing that. I'm new in django and I want to create a dashboard panel for my website. thanks for your replies. -
python dajngo I can`t run it How to slove this issue?
django models.py old code class register(models.Model): name = models.CharField(verbose_name = "名字",max_length = 20) password = models.CharField(verbose_name = "密码",max_length = 20) e_mail = models.CharField(verbose_name = "邮箱",max_length =15 ) tele = models.CharField(verbose_name = "电话",max_length = 11) def __str__(self): return self.name class Meta: verbose_name = ('注册') verbose_name_plural = verbose_name new code class register(models.Model): name = models.CharField(verbose_name = "名字",max_length = 20) brithday = models.DateField(verbose_name="生日", default='10') age = models.IntegerField(verbose_name = "年龄",default = '10') password = models.CharField(verbose_name = "密码",max_length = 20) e_mail = models.CharField(verbose_name = "邮箱",max_length =15 ) tele = models.CharField(verbose_name = "电话",max_length = 11) def __str__(self): return self.name class Meta: verbose_name = ('注册') verbose_name_plural = verbose_name Error:invalid literal for int() with base 10: '' database:sqlite3 -
How to integrate a slack channel with a django website?
So there's this organization I am working for whose most part of communication takes place on a slack channel. So now I need to add a discussion section in their website which is built on python/django which displays all the messages from that specific slack channel and also allows the logged in user to send messages to that slack channel . Basically I just want to take up whole of a channel from slack and make it operational in my website so that users can access it without opening Slack. Thanking you in Advance -
django send image filed oher rest api
I am using Django. My web application structure I have implemented the structure shown in the picture above But I have a problem. There is no problem with images send between clients and bridge hosts. However, I am not sure how to send an image between the host and the bridge host. How should I send it? -
access model attribute in DetailView in Django
I'm using Django 2.x In DetailView, I want to fetch related data. class CourseView(DetailView): template_name = 'courses/detail_view.html' model = Course def get_context_data(self, **kwargs): context = super(CourseView, self).get_context_data(**kwargs) related_courses = Course.objects.search(self.object.name, self.object.teaching_language.title) context['relate_courses'] = related_courses return context The Course model has name fields and related teaching_language.title. Here I'm using self.object.name to get the name of the current object inside view but it seems to be not working. I also tried print(self.object.name) inside get_context_data() but it is printing nothing. How to access current object attributes inside DetailView? -
Populate HTML table with AJAX data in Django
I have the following AJAX script running in my Django template: function create_table() { $.ajax({ method: "GET", url: "/api/data/", success: function(data){ console.log('button clicked') console.log(data) //$('#table').html('<div class="test">' + data['Name'] +'</div>'); //$('#table').load('table_to_load.html'); }, error: function(error_data){ console.log("errorrr") console.log(error_data) } }) } document.getElementById("create_table").onclick = function() { create_table(); return false; } The purpose of this script is to create a HTML table upon button click populated by dictionary data fetched by the AJAX call. The AJAX call collects the data correctly, however, I don't know how to go about inserting the table. Should I write the table HTML in pure Javascript/jQuery inside the AJAX call? Or maybe load a pre-prepared HTML (how do I reference its directory inside the call?)? My preferred method though would be to write the template for the table in Django's template tag language and somehow reference in it the data fetched by AJAX. Something like: <table> <tr> <th>dictionary key</th> <th>dictionary value</th> </tr> {% for key, value in dictionary.items %} <tr> <td>{{ key }}</td> <td> <a href="{{ value }}">{{ value }}</a> </td> </tr> {% endfor %} </table> But I am not sure if it's possible.