Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can't display a value in the template
I am having trouble displaying the value on the html template from the mysql database. my view: from django.contrib.auth.decorators import login_required from django.db.models import Count, Min, Sum, Avg, Max from .models import Gwtable import datetime def index(request): max_value = Gwtable.objects.all().aggregate(Max('salesprice')) my html: {{ max_value.values|floatformat:2 }} -
Change field type in model serializer without changing model
I have a model with a string field with a corresponding model serializer. I'd like to change the serializer so that it now takes a list of strings for that field, but converts that list to a string internally. Basically, internal_repr = input.join(',') I've tried changing the data type in the validate function, but I still get a validation error that it's not a string. Where should this change occur? Is it also necessary to override the serializer on that field to a ListSerializer with child=CharField specified? -
Display localized date with just month and day in a Django template
I want to display a localized date in a Django template with just the month and the day. I currently have {{ value|date:"b d" }} This will display "jan 8" no matter the current locale. So even in french I'll get "jan 8" instead of "8 jan". How can I have it to work correctly for any locale? -
ajax, vanilla javascript, django, views
I want to get ajax response without jquery(regular javascript only). I'm getting whole html page. I need only string from views.py function. file.html: ... <form method="post" > ... <input type="submit" value="Send" id="button"> ... <script type="text/javascript" src="{% static 'js/main.js' %}"></script> <script> var el = document.getElementById("button"); el.addEventListener('click', mainik); </script> main.js: function mainik(e){ e.preventDefault(); XMLHttpRequest.onreadystatechange = backgroundfunc; XMLHttpRequest.open("GET", "/change"); function backgroundfunc() { if (XMLHttpRequest.readyState === XMLHttpRequest.DONE && XMLHttpRequest.status === 200) { console.log(XMLHttpRequest.responseText); } } } XMLHttpRequest.send(); views.py : ... def home(request): ... return render(request,file.html,{}) def back(): heh = "myresp" return HttpResponse(json.dumps(heh)) // I need "myresp" on the screen In Network Monitor I see that url /change works, but response is whole html file instead "myresp" text. I saw some examples with jquery but I can't modify them that would help in my case. I didn't use jquery. I am totally beginner. Please be patient. Thank You : ) -
TypeError: __init__() missing 1 required positional argument: 'on_delete'
Hi i'm trying to run my code and im getting this error: File "C:\Users\JOSHUA\Documents\ypgforum\myproject\boards\models.py", line 13, in <module> class Topic(models.Model): File "C:\Users\JOSHUA\Documents\ypgforum\myproject\boards\models.py", line 16, in Topic board = models.ForeignKey(Board, related_name='topics') TypeError: __init__() missing 1 required positional argument: 'on_delete' Meanwhile this is the models.py it pointed to; class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics') starter = models.ForeignKey(User, related_name='topics') last_updated = models.DateTimeField(auto_now_add=True) -
Relate model to python object
I have some code in which I have defined some Python models. For example: class Store(object): ''' The store object... Should it be a Django model? ''' def __init__(self, *args, **kwargs): self.name = kwargs['name'] self.id = kwargs['id'] def __str__(self, *args, **kwargs): return self.name kittenstore = Store(name='kittenstore', id=1) dogstore = Store(name='dogstore', id=2) stores_list = [kittenstore, dogstore] class Stores(object): def __init__(self, *args, **kwargs): self.stores = stores_list def get_choices(self): store_choices = () for store in self.stores: store_choices+= ((store.id, store.name),) return store_choices I'd like to refer to those stores from another Django model. I could use a models.Integerfield with choices=get_choices(), but when I filter in a related models, then I always get the id back and I need to find the correlating store if I want to use it in my code. Is there not a (python) trick to get back the Store object instead of the id? Maybe with a custom Field? -
API RESTful Resource Naming
I always have the doubt that you can see below when i need to create theresource URLs for a REST API. I wonder if some one can help me. Let's suppose that i have two models. User Post User can submit his own posts and can comment his own and another posts. Main resources URLs for User would be: GET /users # Retrieve all users. POST /users # Create a new user. GET/DELETE/PUT /users/{user_id} # Get, remove and update an user. Main resource URLs for Post would be: GET /posts # Retrieve all posts. POST /posts # Create a new post. GET/DELETE/PUT /posts/{post_id} # Get, remove and update a post. My problem come when for example i want: Top 10 submitters (filter for a parameter(external link, discussion, all)). The URL should be: GET /users/top?type=ext GET /users/top?type=disc GET /users/top # for all Or maybe it should be: GET /users?top=ext GET /users?top=disc GET /users?top=all The same but with posts: Top 10 commented post (filter for a parameter(external link, discussion, all)). The URL should be: GET /posts/comments?type=ext GET /posts/comments?type=disc GET /posts/comments # for all Or maybe it should be: GET /posts?top=ext GET /posts?top=disc GET /posts?top=all Any of above options are good for you … -
how to do a pagination-django with variable 'per_page'?
how to do a pagination with variable 'per_page'. For example, I have 100 articles I wish that the first page (1) contains 3 articles, the second page (2) contains 5 articles, will excite, me who draws of how many articles in each page. see the picture. -
I got the following error while trying to push my Django app to Heroku: TomlDecodeError("Invalid date or number")
When I git push my Django app to Heroku, I get the error below. How do I know what needs to be changed in my code from this error? I'm not sure which date information I misconfigured to raise this error. If you could point me in the right direction, that would be great! remote: File "/tmp/build_913f5397888fc6f8943894f7ab01ea65/.heroku/python/lib/python3.6/site-packages/pipenv/vendor/toml.py", line 454, in _load_line remote: raise TomlDecodeError("Invalid date or number") remote: toml.TomlDecodeError: Invalid date or number remote: ! Push rejected, failed to compile Python app. Here is the full traceback error below: :\Users\Jup\Drop>git push heroku master Counting objects: 19, done. Delta compression using up to 4 threads. Compressing objects: 100% (15/15), done. Writing objects: 100% (19/19), 8.93 KiB | 0 bytes/s, done. Total 19 (delta 8), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.4 (you are using python-3.6.3, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.4). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing requirements with latest Pipenv… remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.6/site-packages/pipenv/project.py", line 272, in parsed_pipfile remote: return contoml.loads(contents) remote: File "/tmp/build_913f5397888fc6f8943894f7ab01ea65/.heroku/python/lib/python3.6/site-packages/pipenv/patched/contoml/__init__.py", line … -
ManagementForm data missing when saving intermediate M2M table
ManagementForm data missing error while formset validation I get this error when I try to save a parent form with intermediate m2m table child formset. I don't know how to solve because the lack of information about this error in Traceback. Please help! models.py class Material(models.Model): name = models.CharField(max_length=200) familiy = models.ForeignKey(Material_family, on_delete=models.CASCADE, null=True) … class Purchase(models.Model): number = models.IntegerField() date = models.DateField() … class Purchase_detail(models.Model): material = models.ForeignKey(Material, on_delete=models.CASCADE) purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE) quantity = models.IntegerField() unit_value = models.IntegerField(default=0) forms.py class PurchaseModelForm(forms.ModelForm): class Meta: model = Purchase fields = (‘number’,’date’ , ’…’) def __init__(self, *args, **kwargs): super(PurchaseModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.form_id = 'id-purchase-form' self.helper.form_method = 'post' class Purchase_detailModelForm(forms.ModelForm): class Meta: model = Purchase_detail fields = ('material','quantity','unit_value') def __init__(self, *args, **kwargs): super(Purchase_detailModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.form_id = 'id-purchase-form' self.helper.form_method = 'post' self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap3/layout/inline_field.html' DetailFormSet = forms.inlineformset_factory(Purchase, Purchase_detail, form=Purchase_detailModelForm, extra=1) views.py def purchase_new(request, purchase_id=None, *args, **kwargs): template = 'erp/purchase_form.html' if purchase_id: inst = Purchase.objects.get(pk=purchase_id) else: inst = Purchase() if request.method == 'POST': form = PurchaseModelForm(request.POST or None, request.FILES, prefix='purchase', instance=inst) formset = DetailFormSet(request.POST or None, request.FILES, prefix='detail') form_valid = form.is_valid() if form_valid: purchase = form.save() formset.save(commit=False) for … -
Django - DateTimeField query on SQLite vs MySQL
This query returns an empty QuerySet in MySQL, but works in SQLite: commented_this_month = Post.objects.filter(comment__created__month=now.month) My models are really simple: class Comment(models.Model): comment = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE) Is there something I am missing? -
Costumize django admin dashboard
In Django 1.11 it's possible customize the dashboard of admin area (index page)? I need to show some table of data or graph. I've tried to override index() method ma it doesn't work. class MyAdminSite(): def index(self, request, extra_context=None): extra_context = extra_context or {} extra_context["test"] = "test" return super(MyAdminSite, self).index(request, extra_context) -
Modify a File with Pillow than save it in database, modifing his attributes first
I'm saving the original file logo = CompLogo(logo=form.cleaned_data['logo'], company=obj) logo.save() my_task.delay(logo.logo.path, obj.pk) then I get the image from the storage using a celery task @task def my_task(path,id): img = crop_image(path) an obtain a new image: def crop_image(path): image = Image.open(path) image_clone = image.copy() image_clone.thumbnail((100, 100)) return image_clone I want to get the new image file and saved in the database but before saving modify his filename. CompLogo.objects.create(logo=crop_image(path), obj_id=obj_id) The above line is not working, I can't change the filename. -
How to use filter in Count Q in Django
I'm trying to sort a query set by its foreign key's number of objects that has been created in the last 7 days. As in if there are three titles like: Title one --> total entry: 100, entries in last 7 days: 5 Title two --> total entry: 10, entries in last 7 days: 8 Title three --> total entry: 50, entries in last 7 days: 2 I want them ordered like: Title two > Title one > Title three This is what I'm trying to get the above generator: all_titles = Title.objects.annotate( num_entries=Count( "entry", filter = Q(entry__entry_date2__gte=make_aware( datetime.datetime.today()-datetime.timedelta(days=7) ) ) ) ).order_by("num_entries") This is what my models look like: class Title(models.Model): title_text = models.CharField(max_length=50, null=True) title_url = models.CharField(max_length=100, null=True) title_channels = models.ManyToManyField(TitleChannels) def __str__(self): return self.title_text class Entry(models.Model): entry_title = models.ForeignKey(Title, on_delete=models.CASCADE) entry_text = models.CharField(max_length=2500, null=True, blank=True) entry_author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) entry_date = models.CharField(max_length=20, null=True, blank=True) entry_points = models.IntegerField(default=0, null=True, blank=True) entry_readability = models.BooleanField(default=True) entry_date2 = models.DateTimeField(null=True, blank=True) def __str__(self): return self.entry_text Instead of ordering it by what I want, I'm getting a list that is sorted by Titles entry_set's length. -
Share image on instagram from Django template
I want to share image on instagram from Django template by using 'image.url'. I have used 'django-social-share' to share image on facebook and twitter. Is there any similar package from which I can share image on instagram? -
Allow user to select random blog bost
I've started using Django 2.0 and Python 3.6.3 to develop a website which will display customized "Posts", as in a blog Post. I want the user to be able to click a button that basically says "Random Post". This button will take them to a template which loads a random blog post. Here's my Post model: class Post(models.Model): post_id = models.AutoField(primary_key=True) ... other fields ... other fields def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Here are some relevant views: class PostListView(ListView): model = Post template_name = 'blog/post_list.html' class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' Here is my problematic view: import random def random_post(request): post_ids = Post.objects.all().values_list('post_id', flat=True) random_obj = Post.objects.get(post_id=random.choice(post_ids)) context = {'random_post': random_obj,} return render(request, 'blog/random_post.html', context) Here I am trying to create a Values List of all post_id values for the Post model. Then I'm trying to get a random choice from this Values List, which would be a random id. Then I'm trying to create a context and render a template using this logic. Here are relevant urlpatterns: urlpatterns = [ path('post/<int:pk>/', views.PostDetailView.as_view(),name='post_detail'), path('post/random/<int:pk>', views.random_post, name='random_post'), Needless to say this is not working. If I leave off the "int:pk" it renders a blank … -
RedirectView.as_view not working at the root
In a django 1.8 project, I am attempting to redirect http://myProject/ads.txt to an external url http://a.location.that.has.the.ads.txt.file and thus serve the ads.txt file without using ftp to simply place the ads.txt in the root. Given this minimal directory structure: django projects myProject myapp urls.py views.py someotherapp yetanotherapp myProject settings.py urls.py (this is the top urls.py) views.py in myProject/myProject/urls.py, (the “top” urls.py) I have as the first entry in the urlpatterns list, the lines: urlpatterns = patterns('', (r'^ads\.txt', RedirectView.as_view(url=http://a.location.that.has.the.ads.txt.file', permanent=False)), followed by many more pattern matching regex’s. This does not work and fails with a 404. What does work is urlpatterns = patterns('', (r'^foo/ads\.txt', RedirectView.as_view(url=http://a.location.that.has.the.ads.txt.file', permanent=False)), and then calling http://myProject/foo/ads.txt Unfortunately, ads.txt files must be placed at the site root. I have tried many different regex’s that test fine in a regex validator, but just don’t work (returns 404). How do I do this without the extra dir “foo”? Any thoughts appreciated. Thank you. -
Django DB-Queryset
Hey i want to get each entry from my database where date = today and time >= now do you know a Django way to do that? in my Model DB is a DateTimeField named date whith the folowing entrys: 2018-01-08 20:00:00, 2018-01-08 20:00:00, 2018-01-08 19:00:00, 2018-01-08 20:00:00, 2018-01-08 20:35:00, 2018-01-08 20:00:50, 2018-01-08 18:00:00, 2018-01-10 20:00:00, 2018-01-09 20:00:00, 2018-02-08 19:00:00, -
an a interviewer ask me what is the command "how to check your model has no error"
an a interviewer ask me what is the command "how to check your model has no error" django have any type of command or not, i think there is no command like this -
Deployed Django instance not recognising a file as a file
I have a deployed django webapp which has been working fine. It scrapes sites for newly published .csv files and then uses them for data analysis which is then returned to the user. The most recent .csv is not being recognised as a file on the deployed version, but is on the test version on my local machine. The structure is as follows: -indicator-analyser -Analyser -AnalysisScripts -uploads -data -2017 -Monthly_File_Jun_Final.csv -Monthly_File_Sep_Final.csv When a user attempts to run the script on the Monthly_File_Jun_Final.csv, the webapp performs as expected. When they run the same script on Monthly_File_Sep_Final.csv, django throws an error as there is no file found. I have taken the file path that is passed in and used that to open the file in explorer, and I have used the same file path to load the .csv as a dataframe in pandas within the console with no problems. The path that is passed to the loading script is: C:\\webapp\\indicator-analyser\\Analyser/uploads/data/2017/Monthly_File_Sep_Final.csv When this is evaluated using os.path.isfile(filepath), it is being returned as False. However, when the other file is selected, this is returned and recognised as a file: C:\\webapp\\indicator-analyser\\Analyser/uploads/data/2017/Monthly_File_Jun_Final.csv Just for reference, this is running on a IIS server. I have restarted the … -
Django 2.0 - Using LoginRequiredMixin and ListView error
I'm trying to make a ListView with a form which when I submit returns me the object list. Below is the code for my views.py. class ChatListView(ListView): model = Chat form_class = NewMessageForm queryset = model.objects.all().order_by('-created_at')[:20][::-1] #returns 20 latest objects template_name = 'chat.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() return redirect('chat') return render(request, self.template_name, {'form': form}) #code for form in the same view def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form_class return context This works for me. But I want this view to only available to log in users. So I added a LoginRequiredMixin. class ChatListView(LoginRequiredMixin, ListView): model = Chat form_class = NewMessageForm queryset = model.objects.all().order_by('-created_at')[:20][::-1] template_name = 'chat.html' login_url = 'login' (Form got saved in the database but the data doesn't show up in the list view.) When I look at the bash the error is "POST /chat/ HTTP/1.1" 302 0. How can I implement the login required thing without this error? -
Django is not writing logs to a local file and how to log the requests
I am trying to log the below requests to a local file. I am using a logging function in settings.py file. Django is creating an empty file but its not writing any thing. Can any one help me what is the wrong i am doing and is it the right logging code to use for logging the below format data? Thank you. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/home/bluedata/mysite/info.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, 'mysite': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } [![These are the requests i want to log.][1]][1] **I WANT TO LOG THESE BELOW PLEASE HELP ME HOW TO DO** [05/Jan/2018 22:26:19] "GET /contact/ HTTP/1.1" 200 1833 [05/Jan/2018 22:26:20] "GET /static/personal/css/bootstrap.min.css HTTP/1.1" 304 0 [05/Jan/2018 22:26:20] "GET /static/personal/img/logo.jpg HTTP/1.1" 304 0 [05/Jan/2018 22:26:22] "GET / HTTP/1.1" 200 5533 [05/Jan/2018 22:26:22] "GET /blog/ HTTP/1.1" 200 1909 [05/Jan/2018 22:26:23] "GET /contact/ HTTP/1.1" 200 1833 [05/Jan/2018 22:26:23] "GET / HTTP/1.1" 200 5533 [1]: https://i.stack.imgur.com/KHh9j.png -
How to retrieve foreign key object from inside a django model validator
I have two models: class Photo(models.Model): # photo attributes and methods class Category(models.Model): banner = models.ForeignKey(Photo, validators=[validate_image_size]) My validator takes the Photo.id ForeignKey, gets the Photo object: def validate_image_size(photo_id): photo = Photo.objects.get(id=photo_id) # open the image using urllib # if image size too large, raise ValidationError() Is there a way to pass the Photo object to the validator? Instead of the photo_id. -
Django - loop through through records and update the record inside the loop?
I cant seem to find the documentation for this, but I want to update the record within a loop of a QuerySet example: data = Site.objects.all() for i in data: ... do stuff i.update(field="value") I know I could do it by: data = Site.objects.all() for i in data: ... do stuff Site.objects.filter(pk=i.pk).update(field="value") but this seems inefficient as I already have the record, so shouldn't need to query for it again. Thanks -
Python 3.6 - Celery not communicating with Redis backend - Using Heroku and Django
I am trying to get asynchronous tasks working with Heroku. I believe Celery is not communicating with the Redis backend properlly. If you could help me troubleshoot, that would be awesome. Thank you a thousand times. I followed these tutorials : Django with Celery: http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html Celery with Heroku: https://devcenter.heroku.com/articles/celery-heroku When I run theadd.delay() function (add being a function in my shared_tasks app) it doesn't seem to connect to the Redis Database. It just freezes after I input the delay function until I press control+C. It looks like: C:\Users\Jup\Drop>heroku ps:scale worker=1 Scaling dynos... done, now running worker at 1:Hobby C:\Users\Jup\Drop>heroku run python Running python on shrouded-ocean-19461... up, run.6193 (Hobby) Python .6.3 (default, Nov 14 2017, 17:29:48) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from Buylist.tasks import * >>> add(2,4) 6 >>> mul(3,4,3) 36 >>> add.delay(3,4) I'm supposed to see the tasks running via heroku logs -t -p but of course I don't. I've tried reading over the tutorial many times but I can't figure out what the problem is. The logs looks like: C:\Users\Jup\Drop>heroku logs -t -p worker 2018-01-08T16:13:10.157170+00:00 heroku[worker.1]: Stopping all processes with SIGTERM 2018-01-08T16:13:10.199379+00:00 app[worker.1]: 2018-01-08T16:13:10.199562+00:00 app[worker.1]: worker: Warm shutdown (MainProcess) …