Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Finding the decorator name using django middleware
I had created a decorator to check if a person has session as follows: (comments added for brevity) def session_enabled(func=None, prefix='calling: '): # some preprocessing def session_enabled_wrapper(*args, **kwargs): # check for session in request obj # execute the function and get result onto a variable say result # some API profiling logic return result return session_enabled_wrapper I have used this on some views as follows: @session_enabled @csrf_exempt def view_function(request): # some processing My goal was to check if any function are being accessed without this decorator in place on the logs. So i wrote a middleware as follows: class SessionEnabledMiddleware(object): ''' class that represents middleware called during requests ''' def process_view(self, request, view_func, view_args, view_kwargs): ''' called during the request cycle :param request: request param :param view_func: view function object :param view_args: args passed to view function :param view_kwargs: kwargs passed to view function :return: None ''' print('############# Inside session enabled middleware ###################') if not view_func.__name__ == 'session_enabled_wrapper': print('Function Not session enabled', request.path) else: print('function is session enabled', request.path) I added the above middleware to tuple of MIDDLEWARE_CLASSES in settings.py file. I was happy as this worked, but the happiness was short lived as my APIs started to crash with … -
Foreign Key Error to Itself on Django
So I am trying to create an inline set similar to this image (http://oi48.tinypic.com/4gm5w2.jpg) so I can add multiple prices for different sizes for a product. I can't get it to even display the area in the django admin. On top of that by doing so I get the error: <class 'apps.main.admin.PriceInline'>: (admin.E202) 'main.Apparel_Price' has no ForeignKey to 'main.Apparel_Price'. models.py: @python_2_unicode_compatible class Apparel_Product(models.Model): product_name = models.CharField(_("Name"), max_length=255) default='media/None/no-img.jpg') product_gender_type = models.CharField(max_length=256, choices=[('male', 'Male'), ('female', 'Female'), ('unisex', 'Unisex')]) product_brand = models.CharField(_("Brand"),max_length=25) product_sizes = models.CharField(_("Sizes"),max_length=25) product_colors = models.CharField(_("Colors"),max_length=25) product_price = models.CharField(_("Price"),max_length=10) product_description = models.CharField(_("Description"),max_length=500) product_shipping_options = models.CharField(_("Shipping Options"),max_length=250) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("Apparel Product") verbose_name_plural = _("Apparel Products") def __str__(self): return self.album_name @python_2_unicode_compatible class Apparel_Picture(models.Model): master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE) product_caption = models.CharField(_("Caption"), max_length=255) product_photo = models.ImageField(_("Picture"), upload_to='media/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("Picture") verbose_name_plural = _("Pictures") def __str__(self): return self.photo_caption @python_2_unicode_compatible class Apparel_Price(models.Model): # master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE) master_apparel_product = models.OneToOneField(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE) product_price = models.CharField(_("Price"), max_length=255) product_size = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = _("Price") verbose_name_plural = _("Prices") def __str__(self): return self.product_price admin.py: from django.contrib import admin … -
custom_ids in batch notification API
I want to use batch notification for communicating between devices. here is the documentation that could help https://batch.com/doc/api/transactional.html I'm using Transactional API part and my code is on Django my question is there is a part of the post request body ,recipients, which is required. I can't understand how should I get custom_ids from. -
Files getting renamed while using file upload in django
I am using file upload control in my Django application (Code is mentioned below). I know Django uses two FILE_UPLOAD_HANDLERS to process file upload request. Memory based: If the file size is smaller than 2.5mb than it uses MemoryFileUploadHandler and saves the files in memory. Disk based: If the file size is larger than 2.5mb then it uses TemporaryFileUploadHandler and saves the files on disk. I am strictly using 2nd approach by removing MemoryFileUploadHandler from request token. What I have observed is that files are getting renamed before getting saved in the /tmp folder. sample_01.pdf --> /tmp/tmpqj9jb13w.upload.pdf sample_02.pdf --> /tmp/tmph1u_6x4r.upload.pdf sample_03.pdf --> /tmp/tmp8p5uoh4g.upload.pdf sample_04.pdf --> /tmp/tmpuwis6ar0.upload.pdf sample_05.pdf --> /tmp/tmpq24bk6tm.upload.pdf Because of this it is getting very difficult to identify the files. Is there any way to keep the name of the files as it is. <div class="custom-file"> <input type="file" class="custom-file-input" id="fileupload" name="fileupload" multiple> <label class="custom-file-label" for="fileupload">Choose files</label> </div> if request.method == 'POST': files_list = request.FILES.getlist('fileupload') -
when using filter in django MultipleObjectsReturned error occur
i am new to django. i see the documentation the model.filter function able to return multiple objects but when using it the following error occur get() returned more than one Jobs -- it returned 2! my code bellow return Jobs.objects.filter(Government=self.Government) -
Django Render template with new dict data
I am currently trying to make a website that shows a summary of git user profiles. Everything works except the data updating live. All of the ajax side of the code works, I am able to make a post request to the server and receive which username the client wants to show. I am having issue actually making the data show on the site. def index(request): if request.method == 'POST': #Get post data from request unparsed = request.body.decode('utf-8') parsed = loads(unparsed) #Parse the json and get the username print(parsed['gitusername']) username = getUserInfo(parsed['gitusername']) #Ask the api to return json of user info print(username) return render(request, "ui/index.html", username) #Re render the template with the new dict data return render(request, "ui/index.html",getUserInfo("jarmahent")) #initially load the website with this dict data -
Limit ajax autocomplete results
How do you limit the number of search result given that the data is not local. I know local data can be easily limited as shown below. source: function(request, response) { var results = $.ui.autocomplete.filter(myarray, request.term); response(results.slice(0, 10));` This is not working quite well when I get my data externally. Below is my code. $(function() { $("#search").autocomplete({ source: function(request, response) { request = "/accounts/ajax/search/"; }, minLength: 2, select: function(event, ui ){ window.open(ui.item.url,'_self')}, open: function(event, ui) { $('.ui-autocomplete').append("<li><a class = \" text-primary\" href='javascript:document.getElementById(\"search_form\").submit();'> See All Result </a></li>"); }, }); }); -
How to Pull info from another model within a DetailsView template (without ForeignKey)?
I am trying to pull data from two models within a DetailsView template (in Django). There is of course a primary model (eg. Articles) associated with the view, which is easy to access. However, I want to access data from a model (eg. Terms). I do not want to use ForeignKey because I will be using many 'Terms' in each 'Article,' and since ForeignKey will allow me to link to only row in the Terms model, I will have to set-up mutiple ForeignKey fields, which can get messy fast. I was thinking that this could be accomplished using get_context_data or templatetags, but haven't have had any luck yet. Any thoughts? Thanks for your assistance, in advance. -
Django Version 1.8.3 SQL Server v13 is not supported
I'm new to this stuff so I apologize if this is in the wrong place. I've inherited a Debian 7.14 system that has Django version 1.8.3 and Python version 2.7.6. It has a connection to SQL Server. We've just upgraded to SQL Server 2016 and are now getting the error Exception Type: NotImplementedError Exception Value: Sql Server v13 is not supported. How can I upgrade to a newer version of Django for this connection to work again? What version will work with SQL Server 2016? I'm thinking it would be a good idea to upgrade Debian version as well while I'm at it, but I'm unsure whether that will break this further. Any insight or suggestions is greatly appreciated, I've done a ton of research and I'm out of places to turn. -
Return invalid Django form and errors to AJAX
I am working on a django website where I've used crispy-forms to render and AJAX to submit a form to the server. I am stuck trying to return a response with the form contents and errors to the AJAX code in order to display the errors in a div (or above the invalid field) Code forms.py: class SubscriptionForm(forms.ModelForm): class Meta: model = Sub fields = "__all__" def __init__(self, *args, **kwargs): super(SubscriptionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.template_pack = 'bootstrap3' self.helper.form_tag = True self.helper.form_id = 'sub-form-1' self.helper.form_class = 'form-inline' self.helper.form_action = 'landing:subscribe' self.helper.field_template = 'bootstrap3/inline_field.html' self.helper.layout = Layout( Div(Div(css_class='sub-form-notifications-content'), css_class='sub-form-notifications'), InlineField('name', id='subName'), InlineField('email', id='subEmail'), FormActions(Submit('sub-form', 'Notify me'), ), ) def clean_email(self): """ Validate that the supplied email address is unique for the site. """ if Sub.objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError( _("This email address is already in use. Please supply a different email address.")) return self.cleaned_data['email'] form html: <form class="form-inline" id="sub-form-1" method="post"> <input type='hidden' name='csrfmiddlewaretoken' value='tdiucOssKfKHaF7k9FwTbgr6hbi1TwIsJyaozhTHFTKeGlphtzUbYcqf4Qtcetre'/> <!-- success/error messages should come HERE --> <div class="sub-form-notifications"> <div class="sub-form-notifications-content"> </div> </div> <div id="div_id_name" class="form-group"> <label for="subName" class="sr-only requiredField">Name</label> <input type="text" name="name" maxlength="30" required placeholder="Name" class="textinput textInput form-control" id="subName"/> </div> <div id="div_id_email" class="form-group"><label for="subEmail" class="sr-only requiredField">Email address</label> <input type="email" name="email" maxlength="60" required placeholder="Email address" class="emailinput form-control" id="subEmail"/> … -
django searching with blank instead of underscore
models.py class ImageModel(models.Model): name = models.ForeignKey(WorkModel, on_delete= models.CASCADE) image1 = models.ImageField(upload_to = 'static/images',null=True) image2 = models.ImageField(upload_to = 'static/images',null=True) image3 = models.ImageField(upload_to = 'static/images',null=True) thumbnail = ThumbnailerImageField(upload_to='static/thumbnails/', verbose_name='thumbnail', blank=True) views.py class WorkListView(generic.ListView): model = models.ImageModel template_name = 'work_list.html' context_object_name = 'image_list' html {% for image in image_list %} <tr> <td>{{ image.name }}</td> <td> <img src="{{ image.thumbnail.avatar.url }}" alt="why?"> </td> </tr> {% endfor %} when i run it i get image not found it seems to be searching for an image with blanks instead of underscore how do i fix this