Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use a single django codebase across multiple (and isolated) server installs and multiple databases
We would like to use the same django codebase to offer our service to multiple companies where each company would have their own install, own database completely isolated from the rest. Looking to find the best strategy to do this. We are at the planning stage. However we have identified the following requirements and potential problems/extra workloads. Requirements 1.) The codebase should be identical. 2.) Each install should have its own database which stores company specific records such as employee details, and also content to be delivered to the front end (copy and such like). Each company must have its own database. Potential problems 1.) Currently when we make database structural changes, we apply these using the django migration system. However, we currently have one install with hundreds of migrations, a new install would not need all of these, only the current version of the models. So we'd end up having to keep track of and produce and version control multiple different sets of migrations. How best to approach this. 2.) Some of the migrations we have in our project are data only, and they are simply not relevant to any new installations. It's also possible that going forward we … -
Django: How to not return all model fields
I'm using a Django system where each model has an associated serializer (pretty standard). In one model, the serializer is as follows: class ThingSerializer(ModelSerializerWithFields): class Meta: model = Thing fields = "__all__" and a model: class Thing(models.Model): class Meta: ordering = ("a", "b") thing_id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True, editable=False) a = models.FloatField(null=True, blank=True, default=None) b = models.FloatField(null=True, blank=True, default=None) I want to implement a system that: if field a of Thing is not null, then field b is returned (on a GET request, for example), and if a is null then b is not returned. How (and where) can I do this? -
How to Filter by Post Arguments in ListView
I am trying to create a form in my ListView which POSTs to the ListView and filters by the POSTed attributes. This is in a Django 2.1 project. I have tried passing both self and request argunments to the post function but I am receiving the Exception below e.g. def post(self, request): results in a TypeError exception: post() takes 1 positional argument but 2 were given If I try to solve the error by removing one of the parameters so that only self is passed to the post() def post(self) function I receive the following TypeError exception: post() takes 1 positional argument but 2 were given Despite the fact that only self has been passed. I have tried only passing request and that results in the same thing. Lots of examples online show def post(self, request, *args, **kwargs) This results in the obvious exceptions of: too many values to unpack (expected 2) Removing all arguments results in a TypeError: post() takes 0 positional arguments but 2 were given class thing_dashboard(ListView): ''' All Orders processed ''' template_name = 'thing/orders_dashboard.html' paginate_by = 25 def post(self, request): queryset = Order.objects.all().order_by('-ordered_date') rejected = self.request.POST.get('rejected') if rejected == 'False': queryset = Order.objects.filter(state='rejected') return queryset return … -
Django Ajax: Not able to get data from my view method to template
I'm completely new to Ajax and Django. I'm trying to accomplish a task which to call an ajax method and update the textarea with the data returned from view. What exactly I'm trying to do? The user selects an option from the dropdown and submit, which internally calls an ajax method and Ajax has to call a particular method in my view. Once view should return a data and the same has to be shown on my webpage. The whole process should complete without page reload and dropdown value reset. Currently, I'm able to make ajax call successfully but not able to render the data on the template. Html and Ajax call: {% extends 'login/whitebase.html' %} {% load static %} <html> <head> <title>Log Hunt</title> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'resources/Newstyle.css' %}"> </head> <body> {% block body %} <div class="container-fluid"> <nav class="navbar navbar-inverse navbar-default" role="navigation"> <div class="container-fluid" style="background-color: #003554;position: absolute;top: 0px;right: -15px;width: 1290px;"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <img src="{% static 'images/envestnet-yodlee.svg' %}" style="width: 45%;padding: 8px"> </div> <button style="font-family:'Trebuchet MS';border-color:white;height: 34px;color: white;font-size: 14px;margin-right: 10px" name="YDocs" class="btn btn-outline-primary"> <i class="fas fa-book"></i> … -
mayan-edms's initiasetup command not wokring
I am installing mayan-edms 3.2.1, I followed the steps as explained in the documentation https://docs.mayan-edms.com/chapters/deploying.html. But i am stuck at initialsetup. When i run this command after applying all migrations its started installing package Bootstrap and then after sometime it shows error in installing that package. This are last few lines on running this command. Applying tags.0008_auto_20180917_0646... OK Applying user_management.0001_initial... OK Installing package: Bootstrap (=3.4.1)... Does anyone know what going wrong? Any help is appreciated. -
How to retrieve hierarchical selection data set into bootstrap modal?
I have a django website hierarchical selection data set stored in tables as follows, id parent_id category --------------------------------- 1 NULL Computers 2 NULL Phones 3 2 Nokia 4 3 Samsung 5 NULL Watch I just want to retrieve these data into bootstrap modal(to filter search result) like this site(hit the "Select Location" button). Could anyone tell me how do I achieve this? -
How can I solve an error when I migrate my Django models?
I want to migrate my model for create tables on my local PgSQL DB. It's not the first time that I'm doing that on this configuration but this time, that's fail. My manipulation : 1) I deleted my old database jlb_inventory 2) I recreated the database jlb_inventory empty 3) I deleted "0001_initial" on application's directory /migration 4) I ran command python manage.py makemigrations models.py # Table Etude class Study(models.Model): study_name = models.CharField(max_length=255, null=False) class Inventory(models.Model): watercourse = models.CharField(max_length=255, null=False) town = models.CharField(max_length=255, null=False) number_resorts = models.IntegerField(null=False) inventory_date = models.DateField(null=False) fk_study = models.ForeignKey(Study, on_delete=models.CASCADE) class Resort(models.Model): index_resort = models.IntegerField(null=False) name_resort = models.CharField(max_length=255) fk_inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) class Taxon(models.Model): name_taxon = models.CharField(max_length=255, null=False) gi = models.IntegerField(default=0) class Sample(models.Model): MICRO_HABITAT_CHOICES = ( ('1', 'Habitat1'), ('2', 'Habitat2'), ('3', 'Habitat3'), ('4', 'Habitat4'), ('5', 'Habitat5'), ('6', 'Habitat6'), ('7', 'Habitat7'), ('8', 'Habitat8'), ) taxon_quantity = models.IntegerField(null=False) fk_taxon = models.ForeignKey(Taxon, on_delete=models.CASCADE) fk_resort = models.ForeignKey(Resort, on_delete=models.CASCADE) And my error django.db.utils.ProgrammingError: relation "business_data_entry_taxon" does not exist LINE 1: ...ame_taxon", "business_data_entry_taxon"."gi" FROM "business_... Someone knows what is the problem here ? Thanks! -
How to insert(Add) JSON data in MySql database through Postman or Rest API Framework using Django?
I have started coding in Python using Django and MySql recently.So, I am facing issue in simple inserting data(JSON format) in a table in MySql database.I have tried few things which I am mentioning below.But it did not work.And I am using the following - Python, Django Framework, MySql Database, mysqlclient connector, Rest API Framework, Postman. Please help me out with suggestions. from django.shortcuts import render, redirect from rest_framework.decorators import api_view from rest_framework.response import Response from .models import fetchdata from .serializers import fetchdataSerializers from rest_framework import status,response from rest_framework import viewsets from django.http import HttpResponse @api_view(['GET','POST']) def index(request): if request.method=='POST': try: _json = request.json _name = _json['name'] _email = _json['email'] _password = _json['pwd'] sql = "INSERT INTO tbl_user(user_name, user_email, user_password) VALUES(%s, %s, %s)" data = (_name, _email, _hashed_password,) conn = mysql.connect() cursor = conn.cursor() cursor.execute(sql, data) conn.commit() resp = jsonify('User added successfully!') serializer=fetchdataSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) -
Django Angular Integration index.html file
In my application we have to integrate django+ Angular. In this how can i render index.html as static. Everytime i have to keep {%static before script files.How can we automate this -
__init__() takes 1 positional argument but 2 were given Error on a very simple form function
I have this very simple form but I keep getting the error init() takes 1 positional argument but 2 were given Here is my code: models.py class Feedback(models.Model): name = models.CharField(max_length=100) contact = models.CharField(max_length=12) title = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) summary = models.TextField(blank=False, null=False) created_on = models.DateTimeField(auto_now_add=True) forms.py class Feedback_form(BSModalForm): class Meta: model = Feedback fields = ['name', 'contact', 'title', 'description', 'summary'] views.py @login_required class Feedback_Create(BSModalCreateView): template_name = 'classroom/teachers/feedback.html' form_class = Feedback_form success_message = 'Success: Sign up succeeded. You can now Log in.' success_url = reverse_lazy('classroom:feedback_form') urls.py path('feedback/', teachers.Feedback_Create, name='feedback'), feedback.html {% load widget_tweaks %} <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h3 class="modal-title">Create Book</h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="{% if form.non_field_errors %}invalid{% endif %} mb-2"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% for field in form %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" placeholder=field.label %} <div class="{% if field.errors %} invalid{% endif %}"> {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="submit-btn btn btn-primary">Create</button> </div> </form> I do not understand what … -
Django keep getting 104 connection reset by peer caused by adding simple video, can't forward video
I want to add video to my django template. When I add it, video is unforwardable (I can't skip this video to other point, I can just play it from start to the end). Excatly the same issue happens when I open link to video in new browser tab. When I close/refresh this page console shows: [19/Jun/2019 11:22:23] "GET / HTTP/1.1" 200 9386 [19/Jun/2019 11:22:23] "GET /media/audio_and_video/videoplayback_lzlCjOR_Ftjx0GJ.mp4 HTTP/1.1" 200 9431145 [19/Jun/2019 11:22:24] "GET / HTTP/1.1" 200 9386 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 44798) Traceback (most recent call last): File "/usr/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer ---------------------------------------- Model: class Track(models.Model): title = models.CharField(max_length=40, null=True) description = models.CharField(max_length=500, null=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) miniature = models.ImageField(upload_to='images/track', default="defaults/default.png", validators=[validate_miniature_file_extension]) audio_or_video = models.FileField(upload_to='audio_and_video/', default="file_not_found", validators=[validate_track_file_extension]) favourite = models.BooleanField(default=False) def __str__(self): return self.title Template (".fields" because I use vuejs, but link to video works exactly as … -
Sending SMS to user entered data
I am using the Twilio API to send a SMS to a number fetched from the db ,entered by the user in the db. That number comes from the database meaning there are a lot of numbers to send to, but I am unable to understand on how to fetch the user entered number for the to field and for the body the user entered text. Note on Model: The logged in user creates a Person taking all their credentials(Number, email etc) through a form, then the logged in user creates an invite against any created Person (mentioned above). This Invite includes the Message (which I want to use as Twilio Body) Below is my code views.py def send_SMS(self,id): account_sid = os.environ["Twilio_account_sid"] auth_token = os.environ["Twilio_auth_token"] client = Client(account_sid, auth_token) client.messages.create( to= 'a number', from_="my Twilio number", body="Talha Here, Reply in Whatsapp, if you recieved this sms with a screen shoot") models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from datetime import date, datetime from django.dispatch import receiver from django.db.models.signals import post_save class PersonData(models.Model): user_relation = models.ForeignKey( User, on_delete=models.CASCADE) person_email = models.EmailField("Email", max_length=512) person_contact_number = models.PositiveIntegerField("Phone Number", blank=True, null=True) class Invite(models.Model): … -
How to fix django-allauth returning KeyError: ['key']?
I'm trying to add e-mail account verification in my django project, but i have some problems with it. What should i do to solve this trouble? There is my urls.py from django.conf import settings from django.urls import path, re_path, include from api import urls from rest_auth.registration.views import VerifyEmailView, RegisterView urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), re_path(r'^account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email') ] There is my settings.py (as for the subject) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.socialaccount', 'allauth.socialaccount.providers.vk', 'allauth.socialaccount.providers.google', 'allauth.account', 'rest_auth.registration', 'corsheaders', 'mainpage', 'combinator' ] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' E-mail is sending correctly (as i suppose by console), But an attempt to go through verification leads to an error: [19/Jun/2019 16:04:08] "GET /account-confirm-email/MTU:1hdYJH:vsf9c1crzBoGBa70De731JG67eI/ HTTP/1.1" 500 97649 Internal Server Error: /account-confirm-email/MTU:1hdYJH:vsf9c1crzBoGBa70De731JG67eI/ Traceback (most recent call last): File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\rest_framework\views.py", … -
Django datepicker in ModelForm shows incorrect date with instance
I have a ModelForm in forms.py as - class MyForm(forms.ModelForm): from_date = forms.DateField(input_formats=['%d-%m-%Y'], label='From Date', widget=forms.TextInput( attrs={'placeholder': 'Select a date', 'class': 'datepicker'}) ) to_date = forms.DateField(input_formats=['%d-%m-%Y'], label='To Date', widget=forms.TextInput( attrs={'placeholder': 'Select a date', 'class': 'datepicker'}) ) class Meta: model = MyModel fields = ['from_date', 'to_date', 'reason'] And the related js - $('.datepicker').flatpickr({ dateFormat: "d-m-Y", allowInput:true, }); With a create form, everything works fine and object gets created successfully. However, on editing the object, the initial date shown on the form is incorrect (Probably the %Y-%m-%d gets parsed as %d-%m-%Y). How to show the correct date in the update form? I tried setting the initial in __init__ but it didn't work. -
ModuleNotFoundError: No module named 'impassionuser'
I'm using django on vscode, and typed this on terminal: (impassion) Subinui-MacBook-Pro:impassion_community subin$ python3 manage.py makemigrations but can't use makemigrations got this error message ModuleNotFoundError: No module named 'impassionuser' how can I solve this problem? I'm using MacOSX, VSCode, django and setup virtualenv I expected to see follow messages Migrations for 'impassionuser': impassionuser/migrations/0001_initial.py -Create model impassionuser -
How to scale y-Axis in d3.js according to data input correctly
I created a small Barchart. My problem is that the y-axis doesn't scale according to my dataset. Here is a screenshot: So as you can see the 313 is a little bit above the 800 scale. I would like the 300 to be at the 300. I tweaked with the scalings but I just end up messing it up completely. I am very new to D3.js so I hope someone can help. Here is my code: var svgWidth = 1000, svgHeight = 800; var barWidth = svgWidth / month_description.length; var barPadding = 5; var svg = d3.select('svg') .attr("width", svgWidth) .attr("height", svgHeight); var barChart = svg.selectAll("rect") .data(data) .enter() .append("rect") .attr("y", function(d) { return svgHeight - d - 20 }) .attr("x", function(d, i) { return i + 10; }) .attr("height", function(d) { return d; }) .attr("width", barWidth - barPadding) .attr("class", "bar") .attr("transform", function (d, i) { var translate = [barWidth * i, 0]; return "translate("+ translate +")"; }); var text = svg.selectAll("text") .data(data) .enter() .append("text") .text(function(d) { return d; }) .attr("y", function(d, i) { return svgHeight - 20; }) .attr("x", function(d, i) { return barWidth * i + 35; }) .attr("fill", "white"); var xScale = d3.scaleLinear() .domain([0, d3.max(month_description)]) .range([0, svgWidth]); var yScale … -
Sphinx automodule: failed to import module
I'm learning Sphinx to document my Django project. My project structure is like app |- docs |- build |- source |- conf.py |- index.rst |- make.bat |- Makefile |- src |- authentication |- __init__.py |- models.py |- ... |- myapp |- __init__.py |- settings.py |- wsgi.py |- manage.py in the `app/docs/source/conf.py, the path to find doc is set as import os import sys sys.path.insert(0, os.path.abspath('../../src')) and index.rst has content App's documentation! ============================================= .. automodule:: manage :members: .. toctree:: :maxdepth: 2 :caption: Contents: Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` on running make html It generates blank documentation page with default content and no content from the Django application. I have many applications created and each application contains many files. I want to auto-generate documentation from the docstring throughout the Django application. -
How to rewrite serializer in Django for custom models?
I want to write my own serializer for my model with a list objects.I'm using Djongo. I've search a lot and got examples for ModelSerializers. Not working on my own model. -
Loading failed for the <script> with source “http://127.0.0.1:8000/static/js/bootstrap.min.js”
I'm getting the error "Loading failed for the with source “http://127.0.0.1:8000/static/js/bootstrap.min.js”." and my ajax is also not working. I want to delete a django form without refreshing my page def client_delete(request, pk): data = {'success': False} client = Client.objects.get(pk=pk) if request.method == 'GET': try: client.delete() if client: data['success']=True else: data['success'] = False data['error'] = "unsuccessful!" except Client.DoesNotExist: return redirect('/NewApp/clientlist') return JsonResponse(json.dumps(data)) In my client_list.py file, {% block javascript %} <script src="{% static '/js/app.js' %}"></script> <script src="{% static '/js/jquery-3.2.1.js' %}"></script> <script src="{% static '/js/bootstrap.min.js' %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4 /jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/jquery.marquee@1.5.0 /jquery.marquee.min.js"></script> {% endblock %} <script> document.getElementById("print").addEventListener("click", function() { console.log("deleted") alert('ok'); var id = $(this).attr('name'); $.ajax({ type:'GET', url: 'NewApp/clientdelete' + id, data:{ csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(data){ if(data.success == true){ alert("success"); } } }); return(false); }); -
how to solve django.core.exceptions.FieldError?
I have 3 models class Car(models.Model): owner = models.ForeignKey(Driver, on_delete=None) car_type = models.CharField(max_length=3, choices=car_type_choices) class Ride(models.Model): pickup_time = models.IntegerField() dropoff_time = models.IntegerField() car = models.ForeignKey(Car, on_delete=models.CASCADE) class Payment(models.Model): ride = models.ForeignKey(Ride, on_delete=models.CASCADE) amount = models.FloatField() and i have to write a query with 3 conditions: if car_type is A, do A` if car_type is B, do B` if car_type is C, do C` I write the queries but get the this exception: django.core.exceptions.FieldError: Expression contains mixed types. You must set output_field. also when i comment first and second queries, third works and when i just comment third one, first and seconds works but all at the same time does not work. q = Car.objects.annotate( extras=Case( When(car_type='A', then=Count('ride')), When(car_type='B', then=Sum(F('ride__dropoff_time') - F('ride__pickup_time'), output_field=FloatField())), When(car_type='C', then=Sum(F('ride__payment__amount'), output_field=FloatField())) ) ) -
Nested models in Django
Sorry for my English. I want to know how I can build my model so that there is an nesting in the admin panel: House1 -> Apartment-> Room-> Person -> Apartment2 -> Room-> Person House2 -> Apartment-> Room-> Person -> Apartment2 -> Room-> Person House3 -> Apartment-> Room-> Person -> Apartment2 -> Room-> Person and so on. models.py from django.db import models class Alex(models.Model): #first page class title = models.CharField(max_length=300, verbose_name = 'table of contents') titletwo = models.CharField(max_length=300, null=True, verbose_name = 'Description') content = models.TextField(null=True, blank=True, verbose_name='url img') foto = models.ImageField(blank=True, upload_to="images/body/%Y/%m/%d", help_text='150x150px', verbose_name='Ссылка картинки') class Meta: verbose_name_plural = 'body' verbose_name = 'body' #should be inside the Alex tab class Bdtwo(models.Model): #for the second page title = models.CharField(max_length=300, verbose_name='table of contents') content = models.TextField(null=True, blank=True, verbose_name='Description') foto = models.ImageField(blank=True, upload_to="images/body/%Y/%m/%d", help_text='150x150px', verbose_name='url img') class Meta: verbose_name_plural = 'body2' verbose_name = 'body2' admin.py from django.contrib import admin from .models import Alex, Bdtwo class BdAdmin(admin.ModelAdmin): list_display = ('title', 'content', 'foto') list_display_links = ('title', 'content', 'foto') search_fields = ('title', 'content',) admin.site.register(Alex, BdAdmin) admin.site.register(Bdtwo, BdAdmin) Want to see: Admin panel "Alex->(inside)Bdtwo" -
Adding of Songs to an Album in Buckky's Django tutorial
Hy guys, I am following #Bukky's tutorial on django, he taught us how to add albums to our website, but not songs to specific album, i tried doing that, but I am having a bit of challenge doing that. How do i go about writing the view for adding songs. -
django-allauth google callback url not working on production
I have integrated google login using django allauth. For my local it works fine. But for production url it is not working. For production it redirect to localhost:8054/accounts/google/login/callback/?state=U0Y1kkth3jNB&code=4%2FbQFuzMf9I-RTXYJUJ-IhUyx36O-gAV00qFvtQHl3nNHzP_QVDJCfe-5f4a1zR12t_P8PgizD-cc95Hhk497fRyY&scope=profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile expected : mysite.com/accounts/google/login/callback/?state=U0Y1kkth3jNB&code=4%2FbQFuzMf9I-RTXYJUJ-IhUyx36O-gAV00qFvtQHl3nNHzP_QVDJCfe-5f4a1zR12t_P8PgizD-cc95Hhk497fRyY&scope=profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile local (working): in google api Authorised redirect URIs = 127.0.0.1:8000/accounts/google/login/callback/ production : Authorised redirect URIs = mysite.com/accounts/google/login/callback/ -
Stored boolean value isn't showing. - Django
By reading the title, it sounds pretty straight forward, but for me, I'm doing a lot of head scratching wondering where I've gone wrong. Rewinding some, I have a form with a list of checkboxes. The checkboxes which apply are selected and stored once the submit button is pressed. The data is stored, no problem. I see 1s and 0s in the DB. However trying to fetch the value has been tricky. All I want to do is see if the Boolean value for a column equals 1 and if so, show a message to the user. That's it, but none of the Boolean values show at all. If try to see a value in a column that isn't a Boolean field, everything works fine. HTML file: {% if app.checkbox_var1 == '1' %} <li> // Message goes here. </li> {% endif %} I've also tried: {% if app.checkbox_var1 == 1 %} <li> // Message goes here. </li> {% endif %} {% if app.checkbox_var1.value == 1 %} <li> // Message goes here. </li> {% endif %} {% if app.checkbox_var1 == True %} <li> // Message goes here. </li> {% endif %} Not forgetting a simple {{ app.checkbox_var1 }} // Nothing appears … -
Django: Transform dict of queryset
I use the following code to get my data out of the dict. test = self.events_max_total_gross() events = organizer.events.all() for event in events: test.get(event.pk, {}).values() [...] I use this query set to get the data. My question is: Does the transformation at the end makes sense or is there a better way to access the dict (without transforming it first). As I have several of these my approach doesn't seem to follow the DRY principle. def events_max_total_gross(self): events_max_total_gross = ( Event.objects.filter( organizer__in=self.organizers, status=EventStatus.LIVE ) .annotate(total_gross=Sum(F('tickets__quantity') * F('tickets__price_gross'))) .values('pk', 'total_gross') ) """ Convert this [ { 'pk': 2, 'total_gross': 12345 }, { 'pk': 3, 'total_gross': 54321 }, ... ] to this: { 2: { 'total_gross': 12345, }, 3: { 'total_gross': 12345, } ... } """ events_max_total_gross_transformed = {} for item in events_max_total_gross: events_max_total_gross_transformed.setdefault( item['pk'], {} ).update({'total_gross': item['total_gross']}) return events_max_total_gross_transformed