Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add Python for machine learning recommendations on my website?
I have been recently learning HTML, CSS, PHP, and Ajax for web development to, finally, build a concrete and consistent web application. As I already have a great experience with the MySQL database, I have just taken a Lynda course on Python and machine learning (using Pandas and Numpy). Could you, please, help me by telling how can I add Python (if there is a possibility) to my HTML, PHP, and Mysql development? I am fairly new to it and still adapting. I have been creating machine learning algorithms in Python at PyCharm, but I just work with .csv files, or transfer them to plain html files. I would like to add these algorithms to a usable website so that I can actually start recommending products to clients. I heard about Django, researched online about it a little bit, but I believe it will not assist me in these purposes. Also, are these development tools I am using (PHP, MySQL, and Python) still on use today? I, by using and deepening my knowledge about them, can improve both my capabilities as a programmer, and become a potentially employable student? -
How can I do POST request in django?
with exception of requests, are there other ways for doing a POST HttpRequest? Ican only use django libs, so I cannot import requests. In particular, I would like to pass the username and the password in the post request. something like: data = { "username": "user", "password": "pass", } r = request.POST( data ) Anyone knows?" -
Heroku - When I run 'heroku run python manage.py migrate' I get an error
When I try to migrate my project to heroku by running the above error, I get the following: C:\Users\{MyUser}\Desktop\My Site\mysite>heroku run python manage.py migrate Running python manage.py migrate on ? {project name}... ! ! Cannot run one-off process at this time. Please try again later. C:\Users\{MyUser}\Desktop\My Site\mysite>heroku run python manage.py makemigrations Running python manage.py makemigrations on ? {project name}... ! ! Cannot run one-off process at this time. Please try again later. I have tried 'makemigrations' as well. Is this an error? On my end or Heroku's? -
django user models create_date no such column
this's my model models.py class MyUserManager(BaseUserManager): def create_user(self, email, nickname, password=None, create_date = None) if not email: raise ValueError('Users must have an email address') user = self.model( email=MyUserManager.normalize_email(email), nickname=nickname, create_date = create_date, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, nickname, password, create_date): u = self.create_user(email=email, nickname=nickname, password=password, create_date = create_date, ) u.is_admin = True u.save(using=self._db) return u class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email', max_length=255, unique=True, ) nickname = models.CharField( u'닉네임', max_length=10, blank=False, unique=True, default='' ) create_date = models.DateTimeField( u'가입날짜', max_length = 10, blank = False, default=timezone.now ) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['nickname', 'gender', 'birthday', 'create_date'] As for my problem, the create_date is in the migrate and the error : no search column is set. fix code def create_date(self): return self.create_date After fixed migrations column delete create_date 1) How should I fix? 2) why this error? 3) i'll want to used create_date = models.DateTimeField(auto_now_add = True) -
Django youtube video id models
I'm new to Django and what I'm doing might be totally stupid but here's what it is. I'm trying to display youtube videos in my template by loading their youtube id from the database but no videos are displayed. Any ideas? models.py: from django.db import models class Video(models.Model): video_id = models.CharField(max_length = 30) def __str__(self): return self.video_id views.py from django.shortcuts import render from Videos.models import Video def videos(request): full_list = Video.objects.all() return render(request, context=full_list) template <h1>YouTube list</h1> {% if full_list %} <ul> {% for video in full_list %} <li> <iframe width="560" height="345" src="http://www.youtube.com/embed/{{ video.video_id }}?rel=0" frameborder="0" allowfullscreen></iframe> </li> {% endfor %} </ul> {% else %} <p>No videos available</p> {% endif %} -
html form action condition in python
<form action="{%url if page_related_data.task is view 'insert_register_form_values_in_database' or 'registered_user_data_edited' registered_user_edit_or_delete_all_information.id%}" method="post"> I actually want to use 2 methods insert_register_form_values_in_database; registered_user_data_edited (with argument registered_user_edit_or_delete_all_information.id) but if i want to use them in one html page in one form tag how can i use it. -
How to know which field is saved when only() has been used in Django?
I am using Django 1.11, in one of my models I have added actions when the model is saved. However I don't want these actions to be done when only a part of the model is saved. I know that update_fields=('some_field',) can be used to specify which field must be saved. But, when the object has been fetched in the database using the methods only() or defer() I don't see any information about the fields updated in the save() method, update_fields is empty. Thus my question: How can I get the fields saved by Django when only some fields have been fetched ? -
How does .send() find connected receivers? Django
I have been learning about signals, and am now trying to understand the basic, inner mechanics of how a signal is sent - and received. This post concerns the provided signal-objects(pre_save, post_save...etc), not writing custom ones. Looking within the Django code for the model class, .send() is called on the imported signal 'pre_save'. When reading about .send() within the Signal class (found in dispatcher.py), there is a comment that says: ''Send signal from sender to all connected receivers.'' How exactly does .send() go about finding connected receivers? I have read that .connect() ensures that signals are connected to receivers, through 'signal dispatchers', which are instances of the Signal class. Could a basic explanation be that the connect-method, found in the Signal class, takes the receiver name that is given to it as a parameter - and appends it to the specified list 'self.receivers'? And that that list is later checked to for possible receivers within the .send() method? Because that is the way it appears to me from reading the code. It also seems, if my beginners-eyes have been able to read everything correctly, that an empty list is returned by the .send() method if no receivers are found. Is … -
How to make asynchronous ajax requests if the server side work takes plenty of time to finish?
I need advice or sample code to achieve a task related asynchronous ajax request that server side work takes plenty of time to finish its job. Here is the sample scenario; I've a simple CSV file upload form. User submits file Server starts processing CSV file. Server makes queries to external web apis for each line of CSV file. (additional network request/response delays) Server parses each response (regex calculations, additional delays) and stores data into database. Server produces another output CSV file. If the CSV file contains < 100 rows, it works even without using ajax. However I need to make it asynchronous to be able to feed a lot of rows. The critical part is I don't want to have timeouts as long as server side code is working. I want to be able to update client side regularly about the progress of work (log-like update, for example "x record is saved into database") Can you provide me a working dummy sample code (for example, calculating fibonacci numbers) both client side and server side. (if possible django) Thanks. Kind Regards. -
create table with dynamic rows and columns with django html template
I'm trying to create a table with dynamic rows and columns based on the results list with django html template. The number of records and header number could change. I am using two for loops to get the number of rows and the column number. I'm having a hard time trying to output the actual values in the table. The idea was to "index" from the second for loop and applying it to "each" of first loop. I know that the syntax is definitely wrong, but is something that django can do? If not, is there any suggestions that I can research on how to implement this? Thanks!! list = [ {'header_a': foo1, 'header_b': foo2, 'header_c': foo3}, {'header_a': foo1, 'header_b': foo2, 'header_c': foo3}, {'header_a': foo3, 'header_b': foo3, 'header_c': foo3}, {'header_a': foo4, 'header_b': foo4, 'header_c': foo4}, ] Sample Table header_a | header_b | header_c foo1 | foo1 | foo1 foo2 | foo2 | foo2 foo3 | foo3 | foo3 foo4 | foo4 | foo4 or list_2 = [ {'header_c': c_foo1, 'header_d': d_foo1}, {'header_c': c_foo2, 'header_d': d_foo2}, ] Sample Table 2 header_c | header_d c_foo1 | d_foo1 c_foo2 | d_foo2 <table> <thead> <tr> {% for index in list.0 %} <th>{{ index }}</th> … -
outer array of images in Django serializer
Im trying to call image url by book, this is my model: class Book(models.Model): users = models.ManyToManyField(User) creation_date = models.DateTimeField(default = timezone.now) published_date = models.DateTimeField(default = timezone.now) isbn = models.CharField(max_length = 200) class PhotoBook(models.Model): book = models.ForeignKey(Book, on_delete= models.CASCADE, related_name="photos") image = models.ImageField(upload_to = "cover_page", blank = True, null = True) This is my serializer.py class BookSerializer(serializers.HyperlinkedModelSerializer): users = UserSerializer(many = True, read_only = True) photos = serializers.StringRelatedField(many=True) published_date = serializers.DateTimeField(format="%Y-%m-%d", input_formats=None) class Meta: model = Book fields = ("published_date" , "photos", "users", "isbn", "title_book", "cover_page", "pages" ,"copies", "description", "subtitle") Sure im trying with serializer.StringRelatedField but only get an array of text saying this is an object of Photobooktype. The question is , how can i get the array of images in my serializer, knowing the foreing_key is in the PhotoBook object. -
Fetch images sent to your Telegram Bot using Django
I want to fetch image sent by the user to the telegram-bot. And save this image in the database, just want to see this image in the URL/admin. My models.py from django.db import models # Create your models here. class BotUser(models.Model): chat_id = models.BigIntegerField() step = models.CharField(max_length=50, null=True, blank=True) username = models.CharField(max_length=120, null=True, blank=True) fio = models.CharField(max_length=120, null=True, blank=True) city = models.CharField(max_length=120, null=True, blank=True) date_wedding = models.DateField(blank=True, null=True) photo = models.ImageField(null=True, blank=True) date_in = models.DateTimeField(auto_now_add=True, auto_now=False, null=True, blank=True) def __str__(self): return 'user_id = ' + str(self.id) + ' chat_id = ' + str(self.chat_id) + ' ' + self.fio + ' ' + self.username class Meta: verbose_name = 'Telegram User' verbose_name_plural = 'Telegram User' And my views.py import telebot and then mes = 'Hello!' bot.send_message(chat_id, mes) mes = 'What is your name?' bot.send_message(chat_id, mes) user.step = 'input_name' user.save() return HttpResponse('OK') if user.step == 'input_name': user.name = text mes = 'What is your city?' bot.send_message(chat_id, mes) user.step = 'input_city' user.save() return HttpResponse('OK') if user.step == 'input_city': user.city = text mes = 'What is your birthday YYYY-MM-DD.' bot.send_message(chat_id, mes) user.step = 'input_date' user.save() return HttpResponse('OK') if user.step == 'input_date': user.date_wedding = text mes = 'What is your photo?' bot.send_message(chat_id, mes) user.step = 'input_photo' … -
What is the best way to get URl of generated file within Celery task
I got a task to make exports of several big tables in DB asynchronous because right now the amount of records is so big that it takes too much time. So I've successfully moved the code of exporting to the Celery task. It exports and saves the file in a folder on a server. But I am not able to get from the task the whole filename, which I could pass to the rest of code and therefore download it after completing the export process because the only thing Celery task can return is only the state of the result of performing the task (done or not yet or failed). I am using Django/Python + Celery + Redis. Thank you for any advice, it already borders me for several days. -
Running management command that take very long in django
I want to call management command from view in Django. The problem is that execution takes very long and nginx gives me 504 or 502 if I increase timeout. Is there a solution for that? -
Django full text search using indexes with PostgreSQL
After solving the problem I asked about in this question, I am trying to optimize performance of the FTS using indexes. I issued on my db the command: CREATE INDEX my_table_idx ON my_table USING gin(to_tsvector('italian', field1), to_tsvector('italian', field2), to_tsvector('italian', field3), to_tsvector('italian', field4), to_tsvector('italian', field5)); Then I edited my model's Meta class as follows: class Meta: managed = False db_table = 'my_table' indexes = [ GinIndex( fields=['field1', 'field2', 'field3', 'field4', 'field5'], name='my_table_idx' ) ] But nothing seems to have changed. The lookup takes exactly the same amount of time as before (again, this is the lookup script). What am I doing wrong? -
Django - override base class model field
I am using Django1.6 i have: class A(Model): att = CharField() class B(A): pass i want to override the behaviour of 'att' (without touching class A): something like: class B(A): @propert def att(self): return self._att + 'thanks' @att.setter def att(self, value): self._att += value how can i do it? i know this is possible from django 1.10 -
Embedding matplotlib moving chart in django template
I am new to python Django framework. I have matplotlib moving or live chart, It should be embedded in django template. I checked many question relevant to this here but none of them is worked for me. Most of us suggested here is displaying as image, but problem is moving chart with default interface like zoom, drag everything to be integrated. i am struggling to solve . I used this code and got to know it will be displaying as image. def simple(request): import random import django import datetime from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter fig = Figure() ax = fig.add_subplot(111) x = [] y = [] now = datetime.datetime.now() delta = datetime.timedelta(days=1) for i in range(10): x.append(now) now += delta y.append(random.randint(0, 1000)) ax.plot_date(x, y, '-') ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas = FigureCanvas(fig) response = django.http.HttpResponse(content_type='image/png') canvas.print_png(response) return response I used this code for reference. if this is not understandable please comment below, ill try to convey you clearly can any one help me to get fixed this. Thanks in advance. -
Why Python has fast in develop [on hold]
I often read that Python is high-performance in develop speed. But I don`t know why. I search long day. many people says, Django is good for make something quickly. but php has also good framework.(eg.laravel) please tell me, why Python has a high-performance in develop speed. (mobile backend, web backend) -
Left joint existing Django QuerySet
I am trying to left join two query in Django. Is there any way to do that? I tried to combine the result in python but I realized that I have to edit the result more times in my templates so that would be more comfortable me to use left join my queries. Also In my future work would be very useful If I know the method of this. Thank you in advance for your help. My first query (1) and result is: Query (1) query:1=Table.objects.all() .filter(time_stamp__range=(before_now_week, now)). .filter(field__gt=0.01) .filter(field__lte=0.03) .annotate(day=TruncDay('time_stamp')) .values('day') .annotate(time=Count('time_stamp')) .annotate(field_count_1=Count('field')) .values('day','field_count_1') .order_by('-day') Result (1): day field_count_1 -------------------------|----------- 2018-01-17 00:00:00+01:00| 49 2018-01-16 00:00:00+01:00| 139 2018-01-15 00:00:00+01:00| 144 2018-01-14 00:00:00+01:00| 142 2018-01-13 00:00:00+01:00| 141 2018-01-12 00:00:00+01:00| 144 2018-01-11 00:00:00+01:00| 145 2018-01-10 00:00:00+01:00| 95 My first query (2) and result is: Query (2) query=Table.objects.all() .filter(time_stamp__range=(before_now_week, now)). .filter(field__gte=0.03) .annotate(day=TruncDay('time_stamp')) .values('day') .annotate(time=Count('time_stamp')) .annotate(field_count_2=Count('field')) .values('day','field_count_2') .order_by('-day') Result(2) day field_count_2 -------------------------|----------- 2018-01-17 00:00:00+01:00| 2 2018-01-16 00:00:00+01:00| 6 2018-01-14 00:00:00+01:00| 2 2018-01-13 00:00:00+01:00| 4 Desired result: day field_count_2 field_count_1 -------------------------|---------------|-------- 2018-01-17 00:00:00+01:00| 49 | 2 2018-01-16 00:00:00+01:00| 139 | 6 2018-01-15 00:00:00+01:00| 144 | 0 2018-01-14 00:00:00+01:00| 142 | 2 2018-01-13 00:00:00+01:00| 141 | 4 2018-01-12 00:00:00+01:00| 144 | 0 2018-01-11 00:00:00+01:00| 145 | … -
How to mock logging in Django Rest Framework unittest?
I have a unit test that tests whether an unauthorized user can GET a certain url. I want to use unittest.mock to mock the logging in the request. How can I point the decorator to use the correct logger ? My test looks like: @patch(what goes here???) def test_response_list_not_authenticated(self, mock_logging): url = django.core.urlresolvers.reverse("project-api:response-list", args=[6]) response = self.client.get(url, format="json") self.assertEqual(response.status_code, rest_framework.status.HTTP_401_UNAUTHORIZED) self.assertEqual(mock_logging.error.called, True) -
Django: Custom Default manytomany manager with a parameter
Following model allows me to handle translations in the database without adjusting code in order to add a language. class NameString(models.Model) en = models.CharField(max_length=55) de = models.CharField(max_length=55) Example use in model called Item: class Item(models.Model): name = models.ForeignKey(NameString) I use a ReadOnlyModelViewSet to view through an api. Which returns the following json: "results": [ { "id": 1, "name": 3, } ] I would like to replace the id value in name field of the json with the actual name in a given language. This is possible by annotating the queryset as for example: name_field = 'name__{}'.format(self.language()) queryset = Item.objects.annotate(name_value=F(name_field)) If I use a serializer with a value name_value, I get the following json: "results": [ { "id": 1, "name_value": 'cucumber', } ] My question is how do I use following model: class ItemList(models.Model): items = models.ManyToManyField(Item) So that I get a following json: "results": [ { "id": 1, "name": "item_list_1", "items" [ { "id": 1, "name_value": "cucumber" }, { "id": 2, "name_value": "apple" } ], } ] Can I somehow change the way the ItemList model handles the Item ManyToMany field? Some kind of custom default manager, that would handle the field response and add the annotation every time the … -
initiating an imagefield in django forms
I have this requirement that I need to initiate the django image field with an image. Here is the thing, 1 - the image with which I want to initiate is stored in s3. 2 - the image_url should be passed in the URL. 3 - that image_url(from the url) should be passed in the django forms, so that we can get the image in the ImageField, and initiate with that. I want to know, 1 - how can we pass url parameter to forms. 2 - How to initiate the form with image. How can it be done? -
Query a Dynamic Django Model based on Content Type
I would like to know if Django has an option to specify dynamic models from which objects need to be filtered when we write a class which would do some generic operations. To understand my requirement better, below is an example. Lets suppose I have the below models. models.py class AttendanceLog(models.Model) content_type = models.ForeignKey(ContentType, related_name="content_ty.....") object_id = models.PositiveIntegerField(default=0) content_object = GenericForeignKey('content_type', 'object_id') half_day = models.BooleanField(default=False) class Teacher(models.Model): user = models.ForeignKey(User) subject = models.CharField(max_length=100) class Staff(models.Model): user = models.ForeignKey(User) designation = models.CharField(max_length=100) class Student(models.Model): user = models.ForeignKey(User) start_date = models.DateTimeField(blank=True, null=True) And below is a class which would have a function that would let us know if a user has taken a half day off. attendance.py class Attendance(object): def __init__(self, request, content_type): self.user = request.POST.get('user', None) self.content_type = content_type def is_half_day(self): user_half_day = False if self.user: try: user = User.objects.get(id=self.user.id) except Exception: user = None if user: try: check_user = <model_name_can_be_Teacher_Staff_Student>.objects.get(user=user) except <model>.DoesNotExist: check_user = None if check_user: half_day_user = AttendanceLog.objects.filter( content_object=check_user, content_type=self.content_type, half_day=True) if user_half_day: user_half_day = True return user_half_day From the view, all I would need to pass would be the request and the content type of the model. The class method will decide which model to query and … -
Django: what is the difference between "overriding save()" and "using save signal"?
I think that anything that can be done with signal also can be done by overriding save() method in Model. If so, why do we need a signal? I can not find when to use the signal. Thanks -
JSON data parsing in Django AJAX POST Request
I'm getting below error whenever I send a JSON object via AJAX post request in Django. json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Code in html: $("#submit").click(function(){ var finalData{}; finalData.name = $('#name').val(); finalData.email = $('#email').val(); finalData.password = $('#password').val(); finalData.website = $('#website').val(); $.ajax({ url: window.location.pathname, type: "POST", data :finalData, success: function(){ }, error: function(){ } }); }); }); Code in Python: def signup(request): if request.method == 'POST': body = request.body response_json = body.decode('utf-8') x = json.loads(response_json) print(x) return render(request, 'signup.html', {}) else: return render(request, 'signup.html', {}) I'm able to print the response using below command in Python print(request.body) Sample JSON Data Object: { name: test, email: test@gmail.com, password: test, website: www.test.com } What exactly am I missing here?