Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i get field data from "through" ManyToMany object?
I have been having trouble on how to get that "group" data in ProductInsideCombo, this is a ManyToMany object that is linked with "through". I need to get the "group" data, Please help. This is what i tried: for one_product in the_product.products_inside_combo.all().order_by('products_inside_combo__id'): try1 = one_product.group # fail try2 = one_product.products_inside_combo__group # fail too! product_id = one_product.id These are my two models: @python_2_unicode_compatible class ProductInsideCombo(models.Model): parent = models.ForeignKey('Product', related_name='+') child = models.ForeignKey('Product', verbose_name="Products inside the combo", related_name='+') group = models.CharField( max_length=255, choices=( ('group_1', 'Group 1'), ('group_2', 'Group 2'), ), default='group_1', ) def __str__(self): return str(self.id) @python_2_unicode_compatible class Product( models.Model ): name = models.CharField(verbose_name="Name"), max_length=255) slug = models.SlugField(verbose_name="Slug"), max_length=255, unique=True) price = models.PositiveIntegerField(verbose_name='Price', null=True, blank=True) sale_price = models.PositiveIntegerField(verbose_name="Sale Price", null=True, blank=True) products_inside_combo = models.ManyToManyField('self', through='ProductInsideCombo', symmetrical=False, help_text="Only for Combo Products", blank=True) created = models.DateTimeField(default=now) modified = models.DateTimeField(editable=True, auto_now=True) def __str__(self): return "%s" % (self.sku, ) class Meta: verbose_name = "Product" verbose_name_plural = "Products" -
django - InstagramClientError: (404) Unable to parse response, not valid JSON
I have been given the task to replicate a django web app to make it run on a server and a vm running ubuntu server 16.04. Followed all necessary steps to set up the existing django project. After running the command python manage.py runserver it runs with no issues. When I browse to localhost:8000 it throws the aforementioned error: ERROR django.request handle_uncaught_exception Internal Server Error: / Traceback (most recent call last): File "/home/xenomader/slowtours_testenv/env3/local/lib/python2.7/site- packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/xenomader/slowtours_testenv/env3/local/lib/python2.7/site- packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/xenomader/slowtours_testenv/slowtours-bak/front/views.py", line 99, in home medias = insta.get_feed() File "/home/xenomader/slowtours_testenv/slowtours-bak/api/insta.py", line 13, in get_feed medias, next_ = api.user_recent_media(user_id=1304858935, count=8) File "/home/xenomader/slowtours_testenv/env3/local/lib/python2.7/site- packages/instagram/bind.py", line 197, in _call return method.execute() File "/home/xenomader/slowtours_testenv/env3/local/lib/python2.7/site- packages/instagram/bind.py", line 189, in execute content, next = self._do_api_request(url, method, body, headers) File "/home/xenomader/slowtours_testenv/env3/local/lib/python2.7/site- packages/instagram/bind.py", line 131, in _do_api_request raise InstagramClientError('Unable to parse response, not valid JSON.', status_code=response['status']) InstagramClientError: (404) Unable to parse response, not valid JSON. A few people have had similar issues in the past but I just don't see any answer that suits me to solve this problem. I am a junior software developer and I am completely new to python … -
How to insert a videos on a web page using django framework?
I want to create a web page using Django which has a videos inserted into it. Can some one please help me in creating such a page from the start? -
Using wagtail + intermediate / through tables for M2M relations
Is there a way of deferring creation of intermediate through tables on a ParentalManyToManyField of a Page model in wagtail? Basic example: class MyPage(Page): field = ParentlManyToManyField(ModelB, through='OrderedModelB', ...) field2 = ParentalManyToManyField(ModelC, through='OrderedModelC', ...) class OrderedModelB(models.Model): page = models.ForeignKey(MyPage) field = models.ForeignKey(ModelB) order = models.PositiveIntegerField() class Meta: ordering = ['order'] From the example above what I'm trying to do should be pretty clear... I have a page which can consists of ManyToManyField's - which require ordering. But, to do this you have to create the intermediate table... However, since pages can go under moderation you wouldn't want to create these intermediate relations on "publishing" the page. As I understand it this would cause querying the pages (ordered) M2M relations to always return the most recent - which may not be approved or in a draft. So, how can you preserve these relationships + wagtails page revision system? Even then.. You'd still want users editing their pages to see the updated orders they specify which makes this a bit more difficult? -
Installing and using panda library in django application
I am trying to build the front-end structure of the energy usage user interface for my university. This requires retrieving data about each building's energy usage that is stored in excel sheets. Unfortunately, when I try to load the excel sheets, I get the following error even though I have already installed pandas: "import pandas as pd ModuleNotFoundError: No module named 'pandas'" When I tried to reinstall it in the same folder as my project, I even got: "OSError: [Errno 13] Permission denied: '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info'" Please advise on how to resolve this problem. -
How to set a jinja2 variable a value from another variable
In {% set form.username = user.get_username %} I want to make form.username equal to the user's username, so when the form is sent, I know who sent it. However, it raises the error: "Did you forget to register or load this tag?" If I replace this line with {{forms.username}} it works, but it makes necessary for the user to fill the form himself, with whatever he wants, allowing him to chose write some username that is not his. file.html (is included in the home.html): <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% set form.username = user.get_username %} {{ form.file }} <button type="submit">Upload</button> views.py: from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from data.models import UserData from data.forms import UserDataForm def model_form_upload(request): if request.method == 'POST': form = UserDataForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = UserDataForm() return render(request, 'data/ranking_index.html', { 'form': form }) models.py: from django.db import models class UserData(models.Model): username = models.CharField(max_length=40) file = models.FileField(upload_to='userdata/') uploaded_at = models.DateTimeField(auto_now_add=True) forms.py: from django import forms from data.models import UserData class UserDataForm(forms.ModelForm): class Meta: model = UserData fields = ('username', 'file', ) -
Treating a model as an instance of imported class in Django
I have a class for manipulating certain data. In that class I calculate and validate the data. Then, is there a way to apply this calculation and validation to an instance of Django model? I came up with two methods. 1.Make another class to connect model and imported class. 2.Write validation and calculations directly in models.py. Which is better? Is there another good way? If 2 is good, how to do that? Here is a very simple example. # in models.py class Person(models.Modes): name = models.CharField() gender = models.CharField() age = models.IntegerField() # in other files class AboutPerson:# I want to apply this class to above model instance. def __init__(self, name, gender, age): self.name =name self.gender = gender self.age = age def validate_age(self): return self.age >= 20 I wish you could understand my poor explanation... Thank you for helping me. -
From Django, serve PDF to browser with #page=[] setting in URL
I am stuck trying to pass a parameter to a PDF rendered in the browser from Django. I think I want to serve the pdf with #page=[page_num] appended to the url the browser sees it at. This is my attempt at doing this in urls.py (note that I'm still on Django 1.11.4 and so haven't migrated to re_path for these url patterns): url(r'^files/(?P<path>.*)#page=[(?P<page_num>d+)]$', serve, {'document_root' : settings.MEDIA_ROOT}, name='file_url') This is the link in the template: <object id="pdf" width="100%" height="900" data="{% url 'knowledge_manager:file_url' document.ref_file.name document.last_open_page %}" type="application/pdf" > </object> The associated view for the whole page is a generic.DetailView. The error I'm getting is a 'no reverse match' for two parameters aimed at a two-field r.e. Reverse for 'file_url' with arguments '('documents/AutonomyinEvolution.pdf', 4)' not found. 1 pattern(s) tried: ['knowledge_manager/files/(?P.*)#page=[(?Pd+)]$'] It was working fine before I tried to add the page number. Is it worth persisting with this approach or is doing it with say javascript more realistic? -
Django: Can not understand TIME_ZONE configuration
I have tested some timezone configuration to better understand about how django timezone works. But still cannot understand how it works. Have some questions and need your helps Q1. from django.utils import timezone from datetime import datetime 1. TIME_ZONE='UTC', USE_TZ=True - datetime.now() => 2018-02-13 23:26:01.576493 // naive.. 2. TIME_ZONE='Asia/Seoul', USE_TZ=True - datetime.now() => 2018-02-13 23:26:01.576493 // tzinfo=<DstTzInfo 'Asia/Seoul' KST+9:00:00 STD> => Why in 'UTC' case return naive datetime object...? As like in 2, I think it should return the tzinfo=<UTC> object... Q2. from django.utils import timezone from datetime import datetime 1. TIME_ZONE='Asia/Seoul', USE_TZ=True - timezone.now() => 2018-02-13 23:25:32.768780 // tzinfo=<UTC> object 2. TIME_ZONE = 'Asia/Seoul', USE_TZ = False - timezone.now() => 2018-02-14 08:24:04.810045 // naive => why does timezone.now() returns tzinfo=<UTC> object in first case, even though I set the TIME_ZONE as 'Asia/Seoul'? Q3. 1. TIME_ZONE = 'Asia/Seoul', USE_TZ = False - timezone.localtime() => ValueError: localtime() cannot be applied to a naive datetime Why does it occur error even though I set a TIME_ZONE? Additionally, cannot understand what exactly USE_TZ is (its role..etc) even after reading django official docs. I think that official documentation is like, easy to read only for the one who already knows what those are.. T_T -
JS Trouble iterating over an HTMLCollection
This should be pretty straight forward. I have a loop, which works, and a variable collecting html code with getElementsByClassName. var inputs = document.getElementsByClassName('inputfile'); if (inputs) console.log(inputs); Output HTMLCollection [] 0: <input id="id_avatar" class="inputfile" name="id_avatar" data-multiple-caption="{count} files selected" multiple="" type="file"> id_avatar: <input id="id_avatar" class="inputfile" name="id_avatar" data-multiple-caption="{count} files selected" multiple="" type="file"> length: 1 It successfully finds the html piece I'm looking. Next I try to feed it through a loop. Array.prototype.forEach.call(inputs, function(input) { console.log("running"); var label = input.nextElementSibling, labelVal = label.innerHTML; }); This does not work. The loop is completely looked over, and is never executed. However if I feed var herp = ["1"]; into the loop, I will see the console print log "running". What is going on? Var inputs is valid to iterate over. Why is it being ignored and/or treated as empty? Thanks in advance. -
Update/put request in Django rest framework
I am new to Django rest framework and trying it for a new project I am working on. So based upon the official tutorial , I am trying to create several get/post/put requests but with put request but I am getting the following error. Expected view ExampleModelView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. Here are my necessary files: models.py class ExampleModel(models.Model): foo_field = models.CharField(primary_key=True, max_length=15) bar_field = models.CharField(max_length=30) last_updated_by = models.CharField(max_length=15) last_updated_on = models.DateTimeField() class Meta: managed = True db_table = 'example_db' unique_together = (('type', 'key'),) serializers.py class ExampleSerializer(serializers.ModelSerializer): class Meta: model = ExampleModel fields= ('foo_field','bar_field','last_updated_by','last_updated_on') urls.py url(r'^get_reference_master/$', views.ExampleUpdateView.as_view()), url(r'^update_reference_master/(?P<type>\d+)/$',views.ExampleUpdateView.as_view()), views.py class ExampleCreateView(generics.CreateAPIView): serializer_class = ExampleSerializer queryset = ReferenceMaster.objects.all() class ExampleUpdateView(generics.UpdateAPIView): queryset = Example.objects.all() serializer_class = ExampleSerializer I think the problem I might have is that I have a composite key. I tried other generics(CreateAPIView & ListAPIView) and they work fine absolutely fine.Do I need to update the def_update method. Do I need to change anything in serializers.py? This is an existing JSON object that I got from my GET request and was trying to update: { "foo_field": "john", "bar_field": "doe", "last_updated_by": "batman", … -
How to remove many to many from a queryset in Django
I have a queryset Class SmallFoo(Model): text = models.CharField() Class Foo(Model): small_foo = models.ManyToManyField(SmallFoo) e.g.Foo.objects.filter(id__in=[2,4,6]).update(small_foo__remove=[1,2]) I want to do something like above i.e. for a query-set update the manytomany field for all of them. Is it possible to do that? I do not want to iterate over each object in queryset and fire separate queries for them. (It takes too much time) -
Django's SuccessMessageMixin not working with DeleteView
Following https://docs.djangoproject.com/en/2.0/ref/contrib/messages/#adding-messages-in-class-based-views, I'm trying to add a success message to a DeleteView: from django.views.generic import DeleteView from django.contrib.messages.views import SuccessMessageMixin class SessionDelete(SuccessMessageMixin, DeleteView): model = Session success_url = reverse_lazy('dashboard:sessions') success_message = "Session %(id)s (%(session_type)s) was deleted successfully" However, I've noticed this doesn't work in Django 1.11.9. I found this pull request, https://github.com/django/django/pull/5992, but it appears to have been closed due to inactivity. Do I understand correctly that success messages still don't work correctly with DeleteViews? -
Django and jQuery drag and drop images order
I am building a page where I would like my users to sort images by drag and dropping them using jQuery and Django. Has anyone done this before? Which would be the best approach? Thank you! -
How do I return data and the form in a CreateView with Django?
In one of my apps I have a page where I display data from the database, products in a table. In there, there is also a form for adding a new product and also a filter form, to filter them. For the add new product form: class AddNewProductForm(forms.ModelForm): class Meta: model = Product fields = "__all__" For the fitrer form, I use django-filters: class ProductFilter(django_filters.FilterSet): class Meta: model = Product The view for the whole page: class MyProductsFilterView(LoginRequiredMixin, FilterView): model = Product filterset_class = ProductFilter template_name = "products/my_products.html" context_object_name = "my_products" form = AddNewProductForm() edit_form = EditNewProductForm() def get_context_data(self, **kwargs): context = super(MyProductsFilterView, self).get_context_data(**kwargs) context["my_products"] = Product.objects.filter(user=self.request.user).select_related().order_by("-timestamp") context["form"] = self.form context["edit_form"] = self.edit_form return context The view for filtering: class ProductCreateView(LoginRequiredMixin, CreateView): template_name = "products/my_products.html" model = Product form_class = ddNewProductForm def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return HttpResponseRedirect("/my-products/") If the AddNewProductForm is valid, based on the ProductCreateView, it renders my_products.html passing AddNewProductForm with the errors. I need to pass the filtered data filter.qs too, so they can be displayed. -
Good practice in using an external api in django
I wonder where I should put the code for api twitter. I have two applications: "accounts" and "twitter". in the "accounts" application I have a code that allows you to login using twitter ('social_django', 'widget_tweaks',). in the "twitter" application, I want to use api twitter. My question is, is it good practice to log in and use the api in the "accounts" application? Can you log in to api in the "twitter" application in the views? accounts/views.py @login_required def settings(request): user = request.user try: twitter_login = user.social_auth.get(provider='twitter') except UserSocialAuth.DoesNotExist: twitter_login = None can_disconnect = (user.social_auth.count() > 1 or user.has_usable_password()) return render(request, 'accounts/settings.html', { 'twitter_login': twitter_login, 'can_disconnect': can_disconnect, }) twitter/views.py from django.views import generic from .models import Tweet from .forms import TweetForm class AppTwitterListView(generic.ListView): model = Tweet def get_queryset(self): return Tweet.objects.filter(user=self.request.user) class AppTwitterDetailView(generic.DetailView): model = Tweet context_object_name = 'tweet_item' class AppTwitterCreateView(generic.CreateView): model = Tweet form_class = TweetForm template_name = "apptwitter/create.html" -
Django unable to load static files
Completely new to django. In my settings.py file, I have: STATIC_URL = '/static/' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] My urls.py has urlpatterns = [ path('admin/', admin.site.urls), path('', views.index) ] And my views.py has def index(request): return render(request, 'index.html', {}) Finally, I have the following in my index.html: {% load static %} <link href="{% static 'styles/custom.css' %}" rel="stylesheet"> The HTML file loads like it showed but the styles don't show up. On inspection, it says that the CSS file was not found. Here is my directory structure: . ├── README.md ├── app │ ├── __init__.py │ ├── db.sqlite3 │ ├── manage.py │ ├── models.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── db.sqlite3 ├── static │ ├── scripts │ │ └── custom.js │ └── styles │ └── custom.css └── templates └── index.html -
Filtering a Django queryset with a limited subquery
I'm trying to get a queryset, and limit based on a limited set of subqueries. It seems to be returning only a limited set of the first query. photos = Photo.objects.filter(event=Event.objects.all().order_by('date')[:5]).order_by('event') I'm trying to get all photo in the five most recent events. -
How to save an image in django in a folder named with the object id?
I have a django backend with this: settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py def portada_inmueble_path(instance, file_name): print('ID', instance.pk) // Here the id or pk is None return '{}/{}/{}'.format( instance.inmobiliaria.id, instance.pk, file_name) class Inmueble(models.Model): ... portada = models.ImageField(upload_to=portada_inmueble_path, blank=True, null=True, max_length=99) ... signals.py @receiver(signals.pre_save, sender=Inmueble) def inmueble_pre_save(sender, instance, **kwargs): new_file = instance.portada try: old_file = Inmueble.objects.get(pk=instance.pk).portada if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path) except: pass I need to name the file path like this: /media/inmobiliaria_id/inmueble_id/portada.jpg My problem is that the id of the inmueble (property) does not exist in the path because it was not created yet. How do I get the id and create the folder with that name? Thanks -
Any way for me to receive DEBUG log/traceback whilst DEBUG is set to FALSE?
I'm running my live Django server on Digital Ocean so have DEBUG=FALSE. Is there any way I can see DEBUG errors? Some function which emails me the traceback or something? -
Pass a form object to other forms in the same page/view()
How do you reference a form that was just created above in the form validation block of a view? If you have a shared model, with two other optionally related models: class Tree(models.Model): type= ... class Picture(models.Model): camera = ... tree=models.ForeignKey(Tree) class Lumber(models.Model): used_to_build = ... tree=models.ForeignKey(Tree) picture=models.ForeignKey(Picture, blank=True, null=True) class Bird(models.Model): species = ... tree=models.ForeignKey(Tree) picture=models.ForeignKey(Picture, blank=True, null=True) You can create a Bird, and Lumber in their own views, and of course reference a specific tree. If you have a view, and you create a form that lets you create a picture of a tree, lumber, and a bird, and you want to pass the newly created Picture to the Lumber and BirdForm, since in this case, we know which Picture the lumber and Bird are in: def treeView(request): #Post pictureForm = PictureForm(instance=tree, prefix='treeForm') # This is what I am trying to figuere out # lumberForm = LumberForm(instance=tree, picture=pictureForm.object prefix='lumberForm') lumberForm = LumberForm(instance=tree, prefix='lumberForm') birdForm = BirdForm(instance=tree, prefix='birdForm') How do you pass in the actual object created to the other forms that can optionally accept the related object? ie ▼ how do you pass in the form object from above? lumberForm = LumberForm(instance=tree, picture=pictureForm.object prefix='lumberForm') -
Creating a custom template tag to replace the for loop - Django
I am trying to simplify my code by creating a custom template tag for a 'for loop' that use frequently on my Django web application. I thought it would be a simple straight process, but something isn't working right... I can use some assistance in catching my error. Here is my code. views.py class ArticleView(DetailView): model = Articles def get_context_data(self, **kwargs): context = super(ArticleView, self).get_context_data(**kwargs) context['s_terms'] = scientific_terms.objects.all() return context template tag @register.filter(name='term') def term(value): {% for term in s_terms %} {{ term.short_description }} {% endfor %} template.html {% Neurons|term %} Thank you for your assistance, in advance. -
Get_absolute_url with ForeignKey doesn't work in Django template
I'm trying to return JsonResponse in Django View: return JsonResponse(render_to_string( 'notifications/notifications_dropdown.html', {'new_notifications': new_notifications}), safe=False) notifications_dropdown.html: {% if new_notifications %} {% for notification in new_notifications %} <a class="dropdown-item" href="{{ notification.task.get_absolute_url }}"> <span class="text-success"> <strong><i class="fas fa-info fa-fw"></i>{{ notification.title }}</strong> </span> <span class="small float-right text-muted">{{ notification.created|date:"SHORT_DATETIME_FORMAT" }}</span> <div class="dropdown-message small">{{ notification.text }}</div> </a> <div class="dropdown-divider"></div> {% endfor %} {% endif %} And my Notification Model has ForeignKey: task = models.ForeignKey(Task, on_delete=models.SET_NULL, null=True) The problem is that {{ notification.task.get_absolute_url }} returns nothing. But when I get the same notification object in shell, it returns correct url. Any ideas, why {{ notification.task.get_absolute_url }} doesn't work in template? Thanks in advance. -
I am trying to run my program on Otree, but i have this error, how can i fix it?
Traceback (most recent call last): File "C:/Users/diese/oTree/normscooperation/normscooperation/models.py", line 1, in import otree.api File "C:\Users\diese\PycharmProjects\untitled\venv\lib\site-packages\otree\api.py", line 3, in from otree.models import BaseSubsession, BaseGroup, BasePlayer # noqa File "C:\Users\diese\PycharmProjects\untitled\venv\lib\site-packages\otree\models__init__.py", line 8, in from otree.db.models import * # noqa File "C:\Users\diese\PycharmProjects\untitled\venv\lib\site-packages\otree\db\models.py", line 12, in from idmap.models import IdMapModelBase File "C:\Users\diese\PycharmProjects\untitled\venv\lib\site-packages\idmap\models.py", line 61, in class IdMapModel(six.with_metaclass(IdMapModelBase, models.Model)): File "C:\Users\diese\PycharmProjects\untitled\venv\lib\site-packages\django\utils\six.py", line 808, in __new_return meta(name, bases, d) File "C:\Users\diese\PycharmProjects\untitled\venv\lib\site-packages\idmap\models.py", line 41, in new cls = super(IdMapModelBase, mcs).new(mcs, name, bases, attrs) File "C:\Users\diese\PycharmProjects\untitled\venv\lib\site-packages\django\db\models\base.py", line 110, in __new__app_config = apps.get_containing_app_config(module) File "C:\Users\diese\PycharmProjects\untitled\venv\lib\site-packages\django\apps\registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "C:\Users\diese\PycharmProjects\untitled\venv\lib\site-packages\django\apps\registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
How to add category to my polls app?
My models.py is class Question(models.Model): question_text = models.CharField(max_length= 100) pub_date = models.DateTimeField('Date Is Published') image = models.ImageField(upload_to="Question_Image", blank=True) def __str__(self): return self.question_text And, I have to add a class "category" so that each of my question could select one of four categories: world, technology, screen and sports.. For example, my one category html i have is screen.html and i need to display only questions based on category 'screen'. Here's my screen.html. {% extends 'polls/base.html' %} {% block main_content %} {% if latest_questions %} <body> <ul style="list-style: none;"> {% for question in latest_questions %} <li style="float:center"> <div id="tabs"><a id="tabsword" href={% url 'polls:detail' question.id %}> <img id="tabsimage" align="middle" src='{{question.image.url}}'/> <p style=" font-size: 25px; font-family: Verdana; color: whitesmoke; text-align: center"><b>{{question.question_text}}</b></p> </a> </div> </li> {% endfor %} </ul> {% else %} <p> You have no questions. Please add some.</p> {% endif %} {% endblock %} Help me modify the codes in a way so that i could add class category, assign each question out of four category and display only questions based on category "screen" on the above html.