Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django REST Framework, how to make SerializerMethodField work for html template?
I made a serializer that uses SerializerMethodField that grabs some foreign fields from models other than the base model defined in Meta class, because I would like these fields to be displayed on the html page. However, calling these foreign fields in html doesn't seem to work. The html (character_list.html): {% block content %} <table> {% for character in characters %} <tr> <td><b>{{ character.name }}</b></td> <!-- This can be correctly shown --> <td>{{ character.primary_description_title }}</td> <!-- The foreign field that doesn't show --> <td>{{ character.primary_description_content }}</td> <!-- The foreign field that doesn't show --> </tr> {% endfor %} </table> {% endblock %} urls.py (relevant part only): ... path('description_list/<int:character_id>/', views.CharacterDescriptionListView.as_view(), name='description_list'), ... views.py (relevant part only): # It has a hell bunch of hierarchy, # But tldr, the serializer it would take is CharacterSerializer in this case class NovelCharacterListView(CharacterViewMixin, CustomNovelListCreateView): template_name = 'polls/character_list.html' def get_filter_object(self): return get_object_or_404(Novel, id=self.kwargs['novel_id']) def get_queryset(self): novelObj = self.get_filter_object() return Character.objects.filter(novel=novelObj) # All the relevant superclasses class CharacterViewMixin(object): _model_class = Character _writable_serializer = CharacterSerializer _read_only_serializer = CharacterReadOnlySerializer _data_name_single = 'character' _data_name_plural = 'characters' class CustomNovelListCreateView(CustomNovelListMixin, generics.ListCreateAPIView): class Meta: abstract = True def get_filter_object(self): raise NotImplementedError('Class %s.get_filter_object is not implemented.' % self.__class__.__name__) # def get_serializer_class(self): # return self._writable_serializer … -
Can't get Django settings inside of my view
I'm trying to pull stripe settings from my cookiecutter base.py, and it's not working. I'm not sure if I have not set my view correctly, or what. I'm testing all of this locally, and I have installed stripe via pip and added it to my installed apps (not sure if I needed to do that) here is my urls.py for the payment view path("payment/", TemplateView.as_view(template_name="pages/Payment.html"), name="payment") And here is my views.py class PaymentView(TemplateView): template_name = 'Payment.html' def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context I've got the following in my base.py STRIPE_SECRET_KEY = 'sk_test_xxxx' STRIPE_PUBLISHABLE_KEY = 'pk_test_xxxxx' I feel my issue isn't that I have the keys in the wrong place. I may just have my view class not named correctly. Any help? Thanks! -
How can I send this variable from django view to html using ajax on key up?
I am making and app that send data in realtime to the user in the html and I want to update the paragraph tag every time the users releases a key. My HTML: <form method="POST"> {% csrf_token %} <p id="amount_word" class="amount_word" style="text-align:center">{{ amount_words }}</p> </form> My javascript ('texteditor' is a textarea that I have): $("#texteditor").keyup(function(event){ data = {'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()}; $.ajax({ type:'POST', url:'/write/', datatype: 'JSON', data: data, success: function(data) { console.log(data) // check out how data is structured $('.amount_word').contents()[0].textContent = data.amount_words } }) }) My python view: def write_view(request, *args, **kwargs): if request.is_ajax() and request.method == "POST": def send_text(): texteditor = request.POST['TextEntered'] amount_words = "Amount of words: " + texteditor print(amount_words) texteditor = request.POST.get('TextEntered') if texteditor == 'NoneType': print("NoneType here") else: send_text() return JsonResponse({'amount_words': amount_words}) return render(request, "write.html") else: return render(request, "write.html") The template is write.html, and the URL is /write -
Django tutorial error: "TypeError at /admin/ - 'set' object is not reversible"
I am going through an official Django tutorial called "Writing your first Django app" and am currently at part 2. Here is the URL: https://docs.djangoproject.com/en/2.2/intro/tutorial02/ When trying to access the admin panel at http://127.0.0.1:8000/admin/, as per the instructions, I receive the following error: Environment: Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 2.2.4 Python Version: 3.7.3 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py" in wrapper 241. return self.admin_view(view, cacheable)(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner 213. if request.path == reverse('admin:logout', current_app=self.name): File "/usr/local/lib/python3.7/site-packages/django/urls/base.py" in reverse 58. app_list = resolver.app_dict[ns] File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py" in app_dict 512. self._populate() File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py" in _populate 463. url_pattern._populate() File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py" in _populate 446. for url_pattern in reversed(self.url_patterns): Exception Type: TypeError at /admin/ Exception Value: 'set' object is not reversible I am on a Mac with Python 3 installed. I looked up all other similar questions for this … -
How to change text of dropdown button after selecting dropdown item?
I'm having some trouble to getting my javascript to work, I was wondering if anyone could give me some guidance on where I can put the javascript code directly in my html file. Is this the correct way of doing it? This is how it looks right now on my screen. Thank you!! -
How do I retrieve a field from a Many-To-Many table?
I need to retrieve a value from a Many-To-Many query. Let's say I have 3 models: Toy, Part, and ToyParts ToyParts has a field called "part_no". I need to be able to get the value of this. class Toy(models.Model): parts = models.ManyToManyField(Part, through="ToyParts") class Part(models.Model): pass class ToyParts(model.Model): toy = models.ForeignKey(Toy, ...) part = models.ForeignKey(Part, ...) part_no = models.CharField(...) I've tried using: Toy.parts.all().first().part_no which obviously doesn't work as Part does not have a field called "part_no" I've also tried just simply using: ToyParts.objects.filter(toy=...,part=...) but that adds additional queries. How would I be able to get part_no without querying ToyParts directly? -
Django ModelFormSet clicking "Submit" saves form but does not update to database
Background: I'm building a personal dictionary web-application, and have a queryset of terms and definitions. In my web app, I have an edit page, where I want to show a ModelFormSet that allows the user to edit any/all entries, and delete them if needed - the form has a delete button for each row and a submit button to save changes to the form. The current issue is that when I click on a set to edit, the formset shows up correctly, and when I change a term and hit "Submit" the form updates to show the change. However, when I go back to my "View Set" page, the term hasn't been updated, which I assume means the change didn't go through to the actual database - the form itself was simply submitted. This is what I would like to currently fix, and I also want to make it so that the delete button deletes the entry. What I've Tried: I've gone through every StackOverflow question I could find relating to the topic, and various solutions were: add an instance parameter when passing in "request.POST", re-initialize the formset after saving, change the "action" url in the HTML page, etc., but … -
I need my Django get_absolute_url to do two different things
So I have a small issue with one of my models when I want to fire get_absolute_url. When someone create's an article on my site I would like it to return them to the 'under-review' page to tell them that there page is currently under review. But the issue is that my sitemap is showing that every article comes up as www.example.com/under-review/ instead of www.example.com/post/example-slug I would normally use return reverse('post-detail', kwargs={'slug': self.slug}) for that which fixes the problem. But then brings up the issue that when someone creates the article, it takes them straight to the page instead of the under-review page. Model: def get_absolute_url(self): # return reverse('post-detail', kwargs={'slug': self.slug}) return reverse('under-review') Ideally I would have it so when someone posts a post, it takes them to the under-review page up at the same time serves the return reverse('post-detail', kwargs={'slug': self.slug}) so it shows up correctly in my sitemap. Thanks. -
django url pattern problem 'NoReverseMatch'
I have 'url(r'^topics/(?P\d+)/$', views.topic, name='topic')' in urls.py but when I try to go to localhost:8000/topics/1 it tells me that it tried one pattern: 'topics/(?P\d+)/$' I would think it would be '*topics/(?P***d+)/$' I'm using a book called The Python Crash Course (1st edition)(ch. 18). This is a local server using Django 1.11 with Python. I've tried a lot of reformatting on the url pattern but I am new at this so I don't know what else to do. ... urlpatterns = [ url(r'^$', views.index, name='index'), # Show all topics. url(r'^topics/$', views.topics, name='topics'), # Detail page for a single topic. url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'), ] I expected it to pop up with the correct page but it always says 'NoReverseMatch at /topics/01/' -
django-rest-framework, passing a foreign key field as url parameter for lookup
I am trying to search for all serial numbers with a specific sales_order(foreign key) field by providing the sales order as a url parameter to its viewset. I'm not sure why my queryset isn't being displayed by a GET request This is a new system I am developing, and as a django newbie I am having some trouble getting everything working the way I'd like it too. Currently, I have configured my routes so that 127.0.0.1:8000/api/serialWSales/ just displays all serial numbers, and I want to have 127.0.0.1:8000/api/serialWSales/(<sales_order>)/ to display only the serial numbers with the sales order number given. I was able to get and print the desired queryset based on the sales_order key, but am having difficulty displaying the queryset with a GET request. I am unsure why the queryset isn't being displayed and the "display: Not Found" exception is being given. Relevant models # Model for Sales table class Sale(models.Model): sales_order = models.CharField(max_length=70, blank=False) model = models.ForeignKey(Model, null=True, on_delete=models.SET_NULL, related_name='sales') quantity = models.IntegerField(blank=False, default=1) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, related_name='sales') sale_id = models.IntegerField(default=1, unique=True, primary_key=True) class Meta: unique_together = [['sales_order', 'model']] verbose_name = 'Sale' verbose_name_plural = 'Sales' db_table = 'tbl_sales' def __str__(self): return self.sales_order def save(self, *args, **kwargs): … -
Save everything for new object except ManyToMany field in Django
I want to save object with ManyToMany relation. When I submit the form, all things save except field that have ManyToMany relation. These are my files: #Forms.py class ExamForm(ModelForm): class Meta: model = Exam fields = '__all__' #Models.py class Exam(models.Model): questions = models.ManyToManyField(Question) title = models.CharField(max_length=250) class Question(models.Model): title = models.CharField(max_length=250) answer = models.TextField(null=True, blank=True) #Views.py def add_exam(request): if request.method == "POST": form = ExamForm(request.POST) if form.is_valid(): new_exam = form.save(commit=False) new_exam.save() return redirect('view_exam') else: form = ExamForm() template = 'add_exam.html' context = {'form': form} return render(request, template, context) What is wrong with these codes? -
Django DateTime serializing
im getting a strange serialized representation of my DateTimeField, at the ending of the representation I get a "-05:00" on the JSON. Inside my model the field is defined as: ultima_actualizacion = models.DateTimeField(auto_now=True) And in the serializer I got it inside the Meta Class: class Meta: fields = ( ... 'ultima_actualizacion', ... ) But when I make a request in the response JSON I get something like: { ... "ultima_actualizacion": "2019-08-07T15:34:22.692530-05:00" } Which seems odd because I haven't changed the format and still get that "-05:00" in every ultima_actualizacion I have looked and tried changing the format and input formats as specified in: Django Rest Framework Fields and in this other answer but still get the "-05:00" -
Monitoring django connections
I'm trying to investigate how well my application is utilising pooled django connections to a mysql database. From mysql, I am able to see the connections and their state, but it appears that the vast majority (often over 99%) of the connections are generally in an idle state. I have been able to monitor the queries made from the django application by following the advice in this post: https://stackoverflow.com/a/24876751/8196202. I am now looking to monitor the connections in a similar way -- i.e. detect when a new connection is created, how long the connection is kept open, and how much of the connection's life is spent in an idle vs active state. I'm wondering if anyone has some tips or suggestions on how to go about gathering this information? My goal is to use the information gathered to try and decide on reasonable values to use for CONN_MAX_AGE, etc. -
Django, When to use multiple template loaders
This is a standard practice question So I have a Django app that contains the standard loader that loads all my web templates from the assets/template folder along with most expected context processors. My app also sends out e-mails in txt and html formats for which I use a different loader. The loaders are set up as follows: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'assets/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, { 'NAME': 'EmailTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'assets/mails')], 'APP_DIRS': True, }, ] When rendering the mails I use get_template(..., using='EmailTemplates') and it works fine. However, my partner argues that the differences between the loaders are minimal and that it's better to make it just one loader and placeassets/mailstoassets/templates/mails`. As Django was build to support multiple template loaders (as evident by the parameters using in the many key template methods, I was wondering: When is it useful to implement multiple template loaders on a site and when should it be avoided? -
Django how to extend generic View class
I noticed that I am setting site-wide context variables and request variables for many views on my site. Naturally, this situation calls for inheritance. If all of my view class-based views are inheriting from SiteView instead of the generic View, I can factor out all the commonalities into the SiteView child class. I can then inherit from SiteView on all my views. But, I cannot get this to work. Here is my code: from django.contrib.auth.decorators import login_required from django.views.generic import View from django.utils.decorators import method_decorator class SiteView(View): ''' Extends the generic django-supplied View class ''' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(SiteView, self).dispatch(*args, **kwargs) def get(self, *args, **kwargs): ''' Adds the variables required in the get request ''' context = super(SiteView, self).get(*args, **kwargs) context['common_var'] = 'some common value' context['user'] = request.user return self.render_to_response(context) This throws the following TypeError: dispatch() missing 1 required positional argument: 'request' Any help would be appreciated -
Defining views and urls in Django. Why aren't parenthesis used to call the function?
I have been going through "Python Crash Course", and I'm working on the "Django Web Application project (Learning Log)" stage. There is something that contradicts what I have already learned... """views.py file""" from django.shortcuts import render def index(request): """The home page for Learning Log.""" return render(request, "learning_logs/index.html") """urls.py file""" from django.urls import path from . import views app_name = "learning_logs" urlpatterns = [ # Home page path("", views.index, name="index") ] In the code above, in "urls.py" file, views.index is called but without parentheses. Why is that? Also, the index function has "(request)" parameter, but the argument is never provided. Am I missing something? Note that this code works fine. -
How can a Ajax/jQuery script show three dependent form dropdown box entries all within one form url?
I am developing a simple form prototype that contains 4 entries in PythonAnywhere (Python 3.7 + Django): PinID (Independent, simple manual number entry) Region (Independent Dropdown Box) Name (Region-Dependent Dropdown Box) Source (Name-Dependent Dropdown Box) What shows up in the Name box is dependent on the Region box, and what shows up in the Source box is dependent on the Name box. So ultimately, the Source Box is dependent on the Region box (If A, then B. If B, then C. So C is dependent on A). To note, if the Region or Name box is blank, their respective dependents are blank. As my current code is written (which is likely wrong), I can only get my Name box to autopopulate correctly. The Source box remains blank, but it does indeed autopopulate correctly after I refresh the page. However, I intend to keep the form all in one url. I refer to two other .html files to "insert" themselves into the form's .html file without refreshing the page. In the jQuery script, I put the identical segment of code for the second dependent dropdown box under the success function of the first dependent dropdown box, which might be my issue. … -
Images as static files in Django (development)
I'm having trouble displaying an image in my home.html template in development. In settings.py, I have this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # for production STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static-assets'), # for development ) The relevant part of the file structure is this: pred_market_pg [base directory] staticfiles [empty] static-assets mp_logo_dark.jpg templates home.html [further templates] markets [all the usual app files] static css markets.css users [all the usual app files, no static folder] In home.html, I then have {% load static %} on top, and further down <img src="{% static 'mp_logo_dark.jpg' %}"/>. I have DEBUG = True and have included django.core.staticfiles in my INSTALLED_APPS in settings.py. Where am I going wrong? -
Django query_params array type instead of string
I have an ApiView that supports get requests: class BookApiView(APIView): def get(self, request): search_criteria = request.query_params When I send a GET request to this end point: http://0.0.0.0:3000/api/book/?q=the+lord+of+the+rings The request.query_params is: <QueryDict: {'q': ['the lord of the rings'], 'page': ['2']}> Instead of being: <QueryDict: {'q': 'the lord of the rings', 'page': '2'}> How can I stop the value from becoming a list or my only option is to parse the value and convert it back to a string? -
Django in production not showing custom 404 page
My django site is in production on digital ocean with ubuntu 18.04 and Django 2.2. It is working with nginx and gunicorn following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 I cannot get it to display my custom 404 page. I have tried setting up the 404 by adding handler404 ='forum.views.error_404' in urls. I added a view function def error_404(request): data = {} return render(request,'forum/error_404.html', data) The rest of my nginx setup is as shown in the tutorial. I think i have to change something in my config for nginx for this to work, something about proxies, but i have no idea how to do it i am completely lost with those config files and which lines to add where. -
How can I add a nullable or boolean field to ManyToManyField Django?
I am trying to add a boolean field which is 'is_featured' column in a pivot table of Portfolio. I want to add images gallery with multiple images but among them there will be a featured image or first one will be featured if there is more than one images is featured. I have found that by 'through' is possible but that do not solve my problem. http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships from django.db import models from tinymce.models import HTMLField from category.models import Category from imageGallery.models import ImageGallery from tag.models import Tag class Portfolio(models.Model): title = models.CharField(max_length=191) description = HTMLField() category = models.ForeignKey(Category, on_delete=models.CASCADE) tag = models.ManyToManyField(Tag, blank=True) # > Here I want to add another column 'is_feature' !!!! gallery = models.ManyToManyField(ImageGallery, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Generally tag will create a pivot table portfolio_portfolio_imageGallery where i want add another column 'is_feature' that could be nullable, or a boolean id portfolio_id imageGallery_id is_feature <- is extra column I want to add. Any help will be greatly appreciated. -
How to store time intervals created dynamically with Javascript in Django
I am working on a Django project with exams, where a unit that makes exams should define prices for the exams made on each interval of the day. So, we need to store intervals of time with start, end and the correspondent price, but the problem is that there is not a fixed number of intervals, then it should be dynamic. I managed to create dynamic fields with Javascript (code bellow), but how can I store this data in a smart way with Django? I will need this later to calculate exam prices. I thought of something like that, but I don't know how to make queries that way: start_time = ArrayField( models.TimeField(null=True, blank=True), null=True, blank=True ) end_time = ArrayField( models.TimeField(null=True, blank=True), null=True, blank=True ) //$('#start-time').mask('00:00'); var max_fields = 10; var wrapper = $(".container1"); var add_button = $(".add_form_field"); var x = 1; $(add_button).click(function(e){ e.preventDefault(); if(x < max_fields){ x++; $(wrapper).append('<input class="two wide field" type="text" name="start[]" placeholder="00:00"/>'); //add input box $(wrapper).append('<input class="two wide field" type="text" name="end[]" placeholder="00:00" />'); $(wrapper).append('<input class="two wide field" type="text" name="price[]" placeholder="0,00"/>'); $(wrapper).append('<br>'); //$(wrapper).append('<a href="#" class="delete">Delete</a>'); } else { alert('Limite de 10 intervalos'); } }); $(wrapper).on("click",".delete", function(e){ e.preventDefault(); $(this).parent('div').remove(); x--; }) });  -
Django model does not update in celery task
I am trying to make a celery task that updates django model and sends email. The emails are sent properly but the model is not saved to the database. Any ideas why does it happen? Here is my sample task: @app.task() def send_invitation(company_id): users = User.objects.filter(company_id=company_id, user_email__invitation_sent=False) for user in users: user.user_email.invitation_sent = True user.save() send_email(user) I have tried several saving options for example user.user_email.save() but when the task finishes, mails are sent but invitation_sent stays False and I can't figure out why this happens -
DRF using another model field in a serializer
I'm moving my first steps with DRf and I'm having problems with this issue. Suppose that I have a model made like this class Snps(models.Model): snpid = models.AutoField(db_column='SNPID', primary_key=True) rsid = models.CharField(unique=True, max_length=20) chrom = models.CharField(max_length=5) pos = models.PositiveIntegerField() class Meta: managed = False db_table = 'SNPs' def __str__(self): return str(self.snpid) class SnpsFunctionalelement(models.Model): snpid = models.ForeignKey(Snps, models.DO_NOTHING, db_column='SNPID', primary_key=True) elementid = models.ForeignKey(Functionalelement, models.DO_NOTHING, db_column='ElementID') celllineid = models.ForeignKey(Celllines, models.DO_NOTHING, db_column='CELLLINEID') filetype = models.CharField(db_column='fileType', max_length=10) class Meta: managed = False db_table = 'SNPs_FunctionalElement' unique_together = (('snpid', 'elementid', 'celllineid', 'filetype'),) def __str__(self): return str(str(self.snpid) + str(self.elementid) + str(self.celllineid) + str(self.filetype)) Now in the serializers.py I want to get the field rsid from Snps and serializing it with the other fields replacing snpid of SnpsFunctionalElement and looking around i found this solution class SnpsFunctionalelementSerializer(serializers.ModelSerializer): rsid = serializers.SerializerMethodField() def get_rsid(self, obj): return obj.Snps.rsid .... but it doesn't work saying that 'SnpsFunctionalelement' object has no attribute 'Snps' and I can't understand what to do -
Is it possible to prefix django models, to run multiple apps on same database
I would like to run multiple different django apps which share the same database. While model specific tables are prefixed with the app, such as appname_tablename, the issue is the Django default tables below are also created. Therefore if I have multiple apps running on the same database these tables are not differentiated. For example, these tables are created automatically. But I would prefer if they were also created with the app prefix, E.G. appname_AUTH_GROUP. Is that possible? • AUTH_GROUP • AUTH_GROUP_PERMISSIONS • AUTH_PERMISSION • AUTH_USER • AUTH_USER_GROUPS • AUTH_USER_USER_PERMISSIONS • CONFIG_FACT • DJANGO_ADMIN_LOG • DJANGO_CONTENT_TYPE • DJANGO_MIGRATIONS • DJANGO_SESSION