Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Load several templates into a base template in django on buttonclick
I have several apps (app1.html, app2.html etc.) and a base.html that has (let's say) 4 placeholders. Now I want to enable the user by clicking on one of the placeholders to choose from these apps and load them into that placeholder. Here's a simple example with js for more clarity: https://jsfiddle.net/eja4t0gb/15/ HTML: <body> <div id="module-1" class=""> This is module 1. <button id="load-1">Load Module</button> </div> --- <div id="module-2" class=""> This is module 2. <button id="load-2">Load Module</button> </div> --- <div id="module-3" class=""> This is module 3. <button id="load-3">Load Module</button> </div> --- <div id="module-4" class=""> This is module 4. <button id="load-4">Load Module</button> </div> --- --- <div id="chooser"> Choose an App. <button id="app-1">App-1</button> <button id="app-2">App-2</button> <button id="app-3">App-3</button> <button id="app-4">App-4</button> </div> </body> </html> Javascript: var chosenModule = null; document.getElementById("chooser").style.display = "none"; for (let i = 1; i <= 4; i++) { document.getElementById("load-" + i).addEventListener("click", function() { chosenModule = i; document.getElementById("chooser").style.display = "block"; }); } for (let i = 1; i <= 4; i++) { document.getElementById("app-" + i).addEventListener("click", function() { loadApp(i); document.getElementById("chooser").style.display = "none"; document.getElementById("app-" + i).style.display = "none"; }); } function loadApp(i) { document.getElementById('module-' + chosenModule).innerHTML = "App" + i; } Here's my question: How would I implement this with django templates/Jinja2? Now I have … -
Indexing JSONField in Django PostgreSQL
I am using a simple model with an attribute that stores all the data for that object in a JSONField. Think of it as way to transfer NoSQL data to my PostgreSQL database. Kinda like this: from django.contrib.postgres.fields import JSONField class Document(models.Model): content = JSONField() Each Document object has (more or less) the same keys in its content field, so I am querying and ordering those documents using those keys. For the querying and ordering, I am using Django's annotate() function. I recently came across this: https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/indexes/ I also know that PostgreSQL using JSONB, which is apparently indexible. So my question is this: Can I index my content field somehow to make my read operations faster for complex queries? And if so, then how do I do it? The documentation page I linked has no examples. -
Running Django Model Query for more than one value for same Field
I would like to know how can we run queries from Django Model if we want to retrieve more than one value for same field For Example This is my Model class Ball(models.Model): Ballname = models.CharField(max_length=8,primary_key=True) Ballcolor = models.CharField(max_length=10) I am trying to get All Balls of Red and White Color dataset = data.filter(Ballcolor="red", Ballcolor ="white") But I get an error saying same field cant be used more than once. How do I get about getting this data ? -
cross origin access issues - django 2.1.7
I have gone through literally all SO links, reinstalled django and django-cors-headers and followed https://github.com/ottoyiu/django-cors-headers/#configuration to the T and yet we get "pre flight error cross origin not allowed". Pasting the relevant sections of settings.py as well. Kindly help Django version - 2.1.7 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'uploads.core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True -
How do I do a social media authentication in django
I want users to be able to register on my website through linkedin and it redirects them to a page with their instance of their username. e.g the redirect url will contain their username http://127.0.0.1:8000/the_username_from_linkedin_profile. This is the url I want the user to be redirected to after registration with linkedin. path(r'<str:username>/', views.dashboard, name='dashboard'), This is the dashboard view. @login_required def dashboard(request, username): """Dashboard page for user""" if request.user.username != username: return redirect(reverse( 'accounts:dashboard', args=(request.user.username,)) ) return render(request, 'accounts/dashboard.html') This is the template that has the button for registration with linkedin. <form id="registrationForm" class='white-popup-block mfp-hide' method='post' action="{% url 'accounts:register'%}"> <div id="reg-errors"></div> <div class="form-group"> {% csrf_token %} {{ reg_form.fullname|add_class:'form-control input-upper my-3' }} {{ reg_form.username|add_class:'form-control input-upper my-3' }} {{ reg_form.email|add_class:'form-control input-upper my-3' }} {{ reg_form.organization|add_class:'form-control input-upper my-3' }} {{ reg_form.password1|add_class:'form-control input-upper my-3' }} {{ reg_form.password2|add_class:'form-control input-upper my-3' }} <small style="color:black" class="text-already"><b>By registering you agree to our</b><a href="{% url 'tos' %}"> terms and conditions</a></small> <div class='text-center'> <img src='/static/images/loader.gif' id='regLoader' class='d-none' /> </div> <div id="regSection"> <button type="submit" class="btn btn-primary btn-block btn-signup-form"> <i class="fa fa-user-plus fa-2x ml-10" aria-hidden="true"></i> SIGN UP </button> <a href="{% url 'social:begin' 'linkedin-oauth2' %}?next={{ next }}" class='btn btn-primary btn-block btn-sign-linkedin'> <i class="fab fa-linkedin-in"></i> &nbsp; &nbsp;Register with Linkedin</i></a> {% comment %} <a href="{% … -
How to return a json in get_queryset()?
I want to return a error message in JSON format from a get_queryset() if error occurs. Does anyone knows hot to do it? def get_queryset(self): try: #some code that returns a queryset except: return Response({"status": "ERROR!"}) But obviously I`m unable to do that. Does anyone knows how to resolve this? One possible way is to somehow convert the message into queryset and return it. But I don`t know how to do it! -
Can I specify an upload-folder in the django models that's derived from a certain value?
I've got a model in Django which has a field specified as following: file = models.FileField(upload_to='data') I want to specify a folder based on a foreign key that another field that this instance has. Is this possible? Can I, for example, use something like file = models.FileField(upload_to='{}/uploads/'.format(self.category.upper())) I haven't tried anything yet. -
Django: Database efficiency
I have two different tasks in my function 1) check if incluencer exists. 2) Increase discount by +1. Currently, I hit the database twice. Is there a better way to write that? Additionally, I wonder I can check 2) all on a database level so I don't need the for-loop. 1) first_order_item = order.order_items.first() influencer = first_order_item.social_ticketing_referral if not influencer: return None 2) for order_item in order.order_items.all(): discount = order_item.get('social_ticketing_discount') if discount: discount.redeemed_amount = F('redeemed_amount') + 1 discount.redeemed_amount.save(update_fields=['redeemed_amount']) break -
Django: Stacking decorators
I have the following signal. Is it possible to 'stack' these two decorators as I did here? @receiver(signal=charge_succeeded) @transaction.atomic def create_influencer_transaction(sender, order, charge, **kwargs): pass -
apply css to a single textbox using jQuery addClass OR a custom LoadCSS function
I am using Django and I want to apply some css to a single textbox. I used the website enjoycss.com to create some css. I have then added this css to the end of Django's base.css: .disabledInput { display: inline-block; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; padding: 10px 20px; border: 6px solid #36c40f; -webkit-border-radius: 3px; border-radius: 3px; font: normal normal bold 15px/normal Georgia, serif; color: rgba(0,142,198,1); -o-text-overflow: clip; text-overflow: clip; background: rgba(252,252,252,1); -webkit-transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1); -moz-transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1); -o-transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1); transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1); } I have a javascript function that I have verified works, using something like this, that has nothing to do with the stylesheet: $(this).css("background", green); But if I comment that out and try to use this, it does not work: $(this).addClass("disabledInput"); Why? In addition, I have created the same .disabledInput all by itself in its own css file named disabled.css. Then, I have tried adding that css file to the textbox attributes, like this: $(this).loadCSS('admin/css/disabled.css'); The LoadCSS function looks like this: $.fn.loadCSS = function(url) { if (!$('link[href="' + url + '"]').length) $(this).append('<link rel="stylesheet" type="text/css" href="' + url + '">'); } … -
An example for embedding bokeh with django templates
Need sequence of steps to display a simple scatterplot in django templates -
How do I override a Django Admin JS File
I want to override DateTimeShortcuts.js on a single model in Django Admin. I believe, based on the docs that I can specify the media files as follows: class MyModelAdmin(admin.ModelAdmin): ... class Media: js = ('path/to/my/js/my_own_javascript.js') This adds the required js, but how do I prevent the original file from being loaded? I currently end up with both JS functions running. -
What is Wrong with my Django logging configuration? No logs are seen in the log file
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'server_logger': { 'level': 'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'maxBytes': 1024*1024*100, 'backupCount': 20, 'filename': os.path.join(BASE_DIR, 'server.log'), 'formatter': 'verbose', }, }, 'loggers': { 'django': { 'handlers': ['server_logger'], 'level': 'DEBUG', 'propagate': True, }, }, } What is wrong with above configuration and why don't see my logs? Any thoughts. -
Filter "get_context_data" using multiple data on a ListView
In my ListView I would like to filter the data by the current user logged from the context_data in : views.py class DashboardListView(LoginRequiredMixin,ListView): model = Links template_name = 'dashboard/home.html' context_object_name ='links_list' paginate_by = 15 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dashboard_list']= Dashboard.objects.filter()[:15] context['todo_list']= Todo.objects.all().order_by('-pk')[:15] context['todo_complete']= Todo.objects.all().count() context['PasswordUsername_list']= PasswordUsername.objects.all() return context I tried to override with a query_set but it does work only for the links model -
Creating dynamically populated one-page multiple-question surveys in Django using forms.py?
I am trying to create a kind of survey app in Django, where questions (called categories) and options are automatically shown on one page. The number of categories and options are arbitrary - the page needs to show everything. Like this: Category 1: Response a Response b Category 2: Response c Response d Response e etc. [submit] I have created a working view, relying heavily on my template and not at all on forms.py. (No form validation yet.) Right now all options are radio buttons, but later I will be making use of different kind of inputs such as checkboxes, text and so on. I am looking for a way to achieve this relying (more) on forms.py and views.py, instead of having most of the logic in my template. Here is my code: models.py: class Category(models.Model): category_name = models.CharField('Kategoriens navn', max_length=100) category_created_at = models.DateTimeField(default=timezone.now, editable=False) class CategoryOption(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) option_name = models.CharField('Knappens navn', max_length=100) option_created_at = models.DateTimeField(default=timezone.now, editable=False) class Response(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) response_created_at = models.DateTimeField(default=timezone.now, editable=False) class ResponseValues(models.Model): response = models.ForeignKey(Response, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) option = models.ForeignKey(CategoryOption, on_delete=models.CASCADE) views.py: def project(request): categories = Category.objects.filter(project=project) # project variable excluded for simplicity … -
How to serve a Django project so that many incoming GET requests are handled in parallel
I have a Django project with some view my_view. My view runs sequentially, but may take a few seconds to complete. I would like to be able to send several GET requests to this view at the same time and have them processed in parallel. Currently, they just run sequentially. How do I achieve this? my_view does not have to be asynchronous. The docker file looks like: FROM python:3.6 RUN apt-get update \ && apt-get install -y --no-install-recommends \ postgresql-client \ && rm -rf /var/lib/apt/lists/* WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] -
Why django is represented as a 'MTV' pattern?
At the django documentation, they mention that In our interpretation of MVC, the “view” describes the data that gets presented to the user. It’s not necessarily how the data looks, but which data is presented. The view describes which data you see, not how you see it. It’s a subtle distinction. ... So, in our case, a “view” is the Python callback function for a particular URL, because that callback function describes which data is presented. ... Where does the “controller” fit in, then? In Django’s case, it’s probably the framework itself: the machinery that sends a request to the appropriate view, according to the Django URL configuration. yeah, I totally agree with them in the case of retrieve. However, in the cases of something that modify (or delete) data, I can't agree with what they mention. Because generally I have implemented view to modify or delete as well. Which doesn't handle "which data is present" but "controlling data". In this sense, view (django says) is not called as a view but as controller I think. Or am I implement view in wrong way? Please let me know the detail of django's "MTV". -
Django - Use AJAX to "stream" the results of a query set with annotations
So I'm loading the counts of each value that exists in a model field. Everything is working fine, but I have to restart my server every time I make a change in the database for the changes to take effect in the front end. I think AJAX might be appropriate for this kind of thing but I don't know how to. Also note that in my query I have annotations which are used in the template. I have my views as follows: def counts(request): duplicates = Application.objects.all().filter(is_qualified="awarded").values('school_name').annotate(name_count=Count('school_name')) context = { 'repeated_names' : records, 'duplicates' : duplicates, 'title' : 'Disbursement Details', } return render(request, 'calculations/list.html', context) and my urls as: path('list/', default_views.counts, name='count_rows'), and finally my template as: <table class="table table-hover" id="disbursement_table"> <thead class=" wow fadeInLeft"> <tr> <th>#</th> <th>School</th> <th>Number of Applicants</th> </tr> </thead> <tbody class=" wow fadeInRight" wow-data-duration="2s"> {% for application in duplicates %} <tr class="clickabe-row" data-target="{% url 'dup_detail' application.school_name %}"> <td>{{ forloop.counter}}</td> <td>{{ application.school_name}}</td> <td>{{ application.name_count }}</td> </tr> {% endfor %} </tbody> </table> -
Django build_absolute_uri() issue : double slashes
I'm using build_absolute_uri() in order to create the beginning of my download link which is sent by email. I'm working with django 1.11.20 My code I have in my code, this view which let to create my url : class FileExport(View): def my_export(self, request, **kwargs): kwargs['user_email'] = request.user.email kwargs['user'] = request.user.name kwargs['url'] = request.build_absolute_uri(reverse('home')) my_export.delay(query_params=request.GET, **kwargs) return render(request, 'app/celery_export.html') The kwargs['url'] is used to create my download link in my message.html file : <a href="{{ url }}{% url 'app:export_download' token=token %}">Download link to your export file</a> I have my urls.py file like this : app_name = 'app' urlpatterns = [ url(r'^home$', HomeView.as_view(), name='home'), url(r'^export/(?P<model>[-\w]+)/(?P<search_info>.*)/$', FileExport.as_view(), name='my_export'), url(r'^export/(?P<model>[-\w]+)/$', FileExport.as_view(), name='my_export'), url(r'^download_export/(?P<token>.*)/$', ExportDownloadView.as_view(), name='export_download'), ] My issue When I receive the email, the link generated inside looks like this : http://localhost:8000//download_export/<my_file>/ As you can see, I'm getting this // which create an issue. By removing one, it works. It works on my qualification environment (distant server), but not in localhost. Do you have some ideas ? Thank you ! -
DRF how can get count of rows from multiple models
I have two models, how can I get the count of rows each of them(using DRF) by one request? class Question(AbstractArticle): title = models.CharField(max_length=256, unique=True) class Service(models.Model): name = models.CharField(max_length=256) -
How to increase a value (pushing a button) in a html django template using a for loop?
I'm actually programming a ask-a-question website for a school project. I followed the first step of the django tutorial from the official website but i'm now trying to improve it myself. I added a 'vote' button in each div (which are created in a for loop) which i want to increase in my views.vote. Some code will be more explainful. So here is my detail.html which shows all my questions and the choices/responses to this question with a vote button for each choice : {% block content %} <h2>{{ question.question_text }}</h2> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <div class="choices"> <label for="">{{ choice.choice_text }}</label><br> <p>{{ choice.votes }} vote{{ choice.votes|pluralize }}</p> <input type="submit" name="vote" id="" value="Vote"> </div> {% endfor %} <br> </form> <a href="{% url 'polls:choice' question.id %}">Add a choice</a> {% endblock %} And here is my views.vote which get the right question and (should) get the right choice's 'votes' value to increase : def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['vote']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += … -
Get avatar in django-rest-framework-social-oauth2
I use django-rest-framework-social-oauth2 for social auth in my django project. I added Google Oauth2 to my project and it works. But I would also like to receive an avatar with the registration of my users through. I use custom UserModel in my project. To add an avatar I tried pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'API.api_v0.service.pipeline.get_avatar', ) In my 'API.api_v0.service.pipeline.get_avatar' i wrote it from account.models import * from social_core.backends.google import GoogleOAuth2 def get_avatar(backend, user, response, *args, **kwargs): print(kwargs) if isinstance(backend, GoogleOAuth2): Account.objects.create_user( username=response.get('email')[:response.get('email').find('@')], email=response.get('email'), avatar=response.get('picture'), ) And it works, but it not giving my Access Token and Refresh Token for this user When I use Pipeline without my custom function 'get_avatar', I get this error { "error": "invalid_grant", "error_description": "Invalid credentials given." } How should I do it right?) -
Django ORM: allow strictly one field to be set (NOT NULL)
I have the following through table for M2M relationship: class ContentOnPage(models.Model): objects = ContentOnPageModelManager() page = models.ForeignKey('Page', on_delete=models.CASCADE) video = models.ForeignKey('Video', null=True, on_delete=models.CASCADE) audio = models.ForeignKey('Audio', null=True, on_delete=models.CASCADE) text = models.ForeignKey('Text', null=True, on_delete=models.CASCADE) order_nbr = models.PositiveIntegerField(default=0) And for video, audio and text fields I want the following constraint - there should be strictly 1 not null value in a row. How could I achieve that? -
Indirectly assign foreign key in DRF request
I need to assign ForeignKey to object without having it in Serializer class. Here's over-simplified version of my case: I have models called Company, User and Order: class Company(models.Model): ... class User(AbstractBaseUser) company = models.ForeignKey('Company', null=False) ... class Order(models.Model): company = models.ForeignKey('Company', null=False) some_other_field = ... ... This way there can be several Companies and each Company can have multiple users and orders. User is allowed to retrieve and create orders. In a ModelViewSet that handles Order retrieval and creation operations I'm filtering queryset against requesting user: .filter(company=self.request.user.company) This way I can leave company field out of Serializer class for Order: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ('some_other_field', ...) Problem arises when user needs to create order using POST request: company field can not be blank, but I don't want to add this field to serializer either because User is always assigned to company thus I internally can add this field by checking which user is sending this request. So far I came up with very brutal solution to override entire create method from CreateModelMixin and assign fields manually after serializer validation: def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) Reservation.objects.create( company=self.request.user.company, some_other_field=request.data['some_other_field'] ) headers = … -
How we access values of dictionary in django templates instead of for loop
I tried to do this like and it give me this error Could not parse the remainder: '[0].title' from 'posts[0].title'